From e2e8040b872e4521ad338f877574ad27c5b11375 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:01:47 +0000 Subject: [PATCH 01/32] feat(transport): freeze the ogiZ0b frame builder contract Signature only; the body is implemented test-first in T1.1. The caller supplies batch_id and session_counter so the builder stays pure. --- src/gflow_cli/api/transports/frame_builder.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/gflow_cli/api/transports/frame_builder.py diff --git a/src/gflow_cli/api/transports/frame_builder.py b/src/gflow_cli/api/transports/frame_builder.py new file mode 100644 index 000000000..3f7ee5b77 --- /dev/null +++ b/src/gflow_cli/api/transports/frame_builder.py @@ -0,0 +1,29 @@ +"""The ``ogiZ0b`` (image generation) batchexecute body, built from domain values. + +A pure function: no I/O, no clock, no randomness. The caller supplies the per-request +values (``batch_id``, ``session_counter``) so the output is deterministic under test. + +Wire shape (proven 2026-11-22, docs/superpowers/spikes/2026-11-22-ogiz0b-minimum-viable-frame.md): + + ctx = [null, 22, null, null, null, project_id, null, null, null, null, [token, 1]] + entry = [null, null, null, session_counter, 2, model, null, ctx, [[[prompt]]], + null, null, null] + inner = [null, [entry], 1, ctx, [batch_id]] + body = urlencode({"f.req": [[["ogiZ0b", json(inner), null, "generic"]]], "at": at}) +""" + +from __future__ import annotations + + +def build_ogiz0b_body( + *, + prompt: str, + model: str, + project_id: str, + recaptcha_token: str, + at_token: str, + batch_id: str, + session_counter: int, +) -> str: + """Return the form-encoded ``f.req`` + ``at`` body for one T2I ``ogiZ0b`` POST.""" + raise NotImplementedError # contract only; implemented test-first in Phase 1 (T1.1) From 959c3960e0bcb4b3c2dbcd3a02c5efce8ec9a306 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:02:41 +0000 Subject: [PATCH 02/32] feat(transport): add GeneratedImage.transport to the contract Optional, defaulting to None, so every existing constructor is unchanged. The direct transport sets it; the recorder and telemetry read it. --- src/gflow_cli/api/dto.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/gflow_cli/api/dto.py b/src/gflow_cli/api/dto.py index 25df7693b..c351e4148 100644 --- a/src/gflow_cli/api/dto.py +++ b/src/gflow_cli/api/dto.py @@ -197,6 +197,9 @@ class GeneratedImage: # is the searchable label the media picker shows — recorded so a generated # image can be referenced by name later. Original find by @C1ph3r404 (#253). display_name: str | None = None + # The transport that produced this image ("direct_http"); None = the default UI path. + # Recorded into the asset's metadata_json and the weekly telemetry, never sent. + transport: str | None = None @property def is_signed_url(self) -> bool: From 135f23d72eccf5538904b0313b8e5a4d70b0f41d Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:12:02 +0000 Subject: [PATCH 03/32] Record generated image transport in asset metadata --- src/gflow_cli/data/_recording_image.py | 2 + tests/data/test_recorder.py | 71 ++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/src/gflow_cli/data/_recording_image.py b/src/gflow_cli/data/_recording_image.py index c52ca3074..0ae25a8ff 100644 --- a/src/gflow_cli/data/_recording_image.py +++ b/src/gflow_cli/data/_recording_image.py @@ -159,6 +159,8 @@ def _persist_generated_image( # persists the browser-searchable caption in plaintext. if image.display_name and self.prompt_mode == "store": metadata["display_name"] = image.display_name + if image.transport is not None: + metadata["transport"] = image.transport repo.upsert_asset( AssetRecord( id=asset_id, diff --git a/tests/data/test_recorder.py b/tests/data/test_recorder.py index 300280aa4..938209629 100644 --- a/tests/data/test_recorder.py +++ b/tests/data/test_recorder.py @@ -92,6 +92,77 @@ def test_record_generated_images_persists_generation_metadata(tmp_path: Path) -> assert "display_name" not in json.loads(asset_row["metadata_json"]) +def test_record_generated_images_persists_transport_when_present(tmp_path: Path) -> None: + saved = tmp_path / "image.png" + saved.write_bytes(b"image-bytes") + with DataStore.open(tmp_path / "gflow.db") as store: + recorder = OperationRecorder(DataRepository(store), prompt_mode="store") + project = ProjectInfo(project_id="flow-project-1", title="gflow-cli t2i") + image = GeneratedImage( + media_name="media-generated-direct", + workflow_id="workflow-generated-1", + seed=123, + prompt="prompt text", + model_name_type="NARWHAL", + aspect_ratio="IMAGE_ASPECT_RATIO_PORTRAIT", + fife_url="https://flow-content.google/path?Signature=abc", + dimensions=(1024, 1792), + transport="direct_http", + ) + req = GenerateImageRequest( + prompt="prompt text", + aspect=Aspect.PORTRAIT, + model=Model.NARWHAL, + ) + recorder.record_generated_images( + profile_name="default", + profile_dir=tmp_path / "profile_default", + project=project, + request=req, + images=[image], + saved_paths=[saved], + input_media_ids=[], + operation_kind="t2i", + ) + asset_row = store.conn.execute( + "SELECT metadata_json FROM assets WHERE flow_media_id='media-generated-direct'" + ).fetchone() + assert asset_row is not None + metadata = json.loads(asset_row["metadata_json"]) + assert metadata.get("transport") == "direct_http" + + +def test_record_generated_images_omits_transport_when_none(tmp_path: Path) -> None: + saved = tmp_path / "image.png" + saved.write_bytes(b"image-bytes") + with DataStore.open(tmp_path / "gflow.db") as store: + recorder = OperationRecorder(DataRepository(store), prompt_mode="store") + project = ProjectInfo(project_id="flow-project-1", title="gflow-cli t2i") + image = _generated_image() + assert image.transport is None + req = GenerateImageRequest( + prompt="prompt text", + aspect=Aspect.PORTRAIT, + model=Model.NARWHAL, + ) + recorder.record_generated_images( + profile_name="default", + profile_dir=tmp_path / "profile_default", + project=project, + request=req, + images=[image], + saved_paths=[saved], + input_media_ids=[], + operation_kind="t2i", + ) + asset_row = store.conn.execute( + f"SELECT metadata_json FROM assets WHERE flow_media_id='{image.media_name}'" + ).fetchone() + assert asset_row is not None + metadata = json.loads(asset_row["metadata_json"]) + assert "transport" not in metadata + + def _generated_image() -> GeneratedImage: return GeneratedImage( media_name="media-generated-1", From b327f11f1e0c305ec35d461d162d46edaf6e3a9c Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:12:19 +0000 Subject: [PATCH 04/32] Add direct_can_serve strategy selector and unit tests --- src/gflow_cli/api/transports/direct_http.py | 30 +++++++++++++++++++ tests/api/transports/test_direct_http.py | 32 +++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/gflow_cli/api/transports/direct_http.py create mode 100644 tests/api/transports/test_direct_http.py diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py new file mode 100644 index 000000000..3dced2ade --- /dev/null +++ b/src/gflow_cli/api/transports/direct_http.py @@ -0,0 +1,30 @@ +"""Direct HTTP transport for image generation on flow.google.com.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from gflow_cli.api.image import Aspect + +if TYPE_CHECKING: + from gflow_cli.api.image import GenerateImageRequest + + +def direct_can_serve(request: GenerateImageRequest) -> bool: + """Return True only for plain T2I requests supported by direct HTTP. + + Excludes reference images (refs, ref_paths), character entities, + non-portrait aspect ratios, multi-image counts, Agent instructions, + and character mentions (@). + """ + if request.aspect is not Aspect.PORTRAIT: + return False + if request.count != 1: + return False + if bool(request.refs) or bool(request.ref_paths) or bool(request.reference_entities): + return False + if bool(request.instructions): + return False + if "@" in request.prompt: + return False + return True diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py new file mode 100644 index 000000000..86801f05d --- /dev/null +++ b/tests/api/transports/test_direct_http.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from gflow_cli.api.image import AgentInstruction, Aspect, GenerateImageRequest, ImageRef +from gflow_cli.api.transports.direct_http import direct_can_serve + + +def test_direct_can_serve_plain_t2i() -> None: + req = GenerateImageRequest(prompt="A cinematic view of mountains") + assert direct_can_serve(req) is True + + +@pytest.mark.parametrize( + "kwargs", + [ + {"refs": (ImageRef(name="00000000-0000-0000-0000-000000000001"),)}, + {"ref_paths": (Path("image.png"),)}, + {"reference_entities": ("entity-1",)}, + {"aspect": Aspect.LANDSCAPE}, + {"aspect": Aspect.SQUARE}, + {"count": 2}, + {"instructions": (AgentInstruction(text="keep lighting dark"),)}, + {"prompt": "A photo of @Alice in wonderland"}, + ], +) +def test_direct_can_serve_excluded_shapes(kwargs: dict[str, object]) -> None: + base = {"prompt": "A cinematic view of mountains"} + req = GenerateImageRequest(**{**base, **kwargs}) + assert direct_can_serve(req) is False From bfef8017c7d7e2ed3fc1fd126ab13651234f732f Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:12:34 +0000 Subject: [PATCH 05/32] Builds pure ogiZ0b request bodies --- src/gflow_cli/api/transports/frame_builder.py | 38 +++++++- tests/api/transports/test_frame_builder.py | 87 +++++++++++++++++++ 2 files changed, 123 insertions(+), 2 deletions(-) create mode 100644 tests/api/transports/test_frame_builder.py diff --git a/src/gflow_cli/api/transports/frame_builder.py b/src/gflow_cli/api/transports/frame_builder.py index 3f7ee5b77..71aec7f1f 100644 --- a/src/gflow_cli/api/transports/frame_builder.py +++ b/src/gflow_cli/api/transports/frame_builder.py @@ -6,7 +6,7 @@ Wire shape (proven 2026-11-22, docs/superpowers/spikes/2026-11-22-ogiz0b-minimum-viable-frame.md): ctx = [null, 22, null, null, null, project_id, null, null, null, null, [token, 1]] - entry = [null, null, null, session_counter, 2, model, null, ctx, [[[prompt]]], + entry = [null, null, null, session_counter, 2, model, null, copy(ctx), [[[prompt]]], null, null, null] inner = [null, [entry], 1, ctx, [batch_id]] body = urlencode({"f.req": [[["ogiZ0b", json(inner), null, "generic"]]], "at": at}) @@ -14,6 +14,11 @@ from __future__ import annotations +import json +from urllib.parse import urlencode + +_ASPECT_PORTRAIT = 2 # Flow's 2026-11-22 submit capture sends 2 for portrait 9:16. + def build_ogiz0b_body( *, @@ -26,4 +31,33 @@ def build_ogiz0b_body( session_counter: int, ) -> str: """Return the form-encoded ``f.req`` + ``at`` body for one T2I ``ogiZ0b`` POST.""" - raise NotImplementedError # contract only; implemented test-first in Phase 1 (T1.1) + ctx: list[object] = [ + None, + 22, + None, + None, + None, + project_id, + None, + None, + None, + None, + [recaptcha_token, 1], + ] + entry: list[object] = [ + None, + None, + None, + session_counter, + _ASPECT_PORTRAIT, + model, + None, + ctx.copy(), + [[[prompt]]], + None, + None, + None, + ] + inner = [None, [entry], 1, ctx, [batch_id]] + f_req = json.dumps([[["ogiZ0b", json.dumps(inner, separators=(",", ":")), None, "generic"]]]) + return urlencode({"f.req": f_req, "at": at_token}) diff --git a/tests/api/transports/test_frame_builder.py b/tests/api/transports/test_frame_builder.py new file mode 100644 index 000000000..c98fcf7d2 --- /dev/null +++ b/tests/api/transports/test_frame_builder.py @@ -0,0 +1,87 @@ +"""Tests for the pure ogiZ0b frame builder.""" + +from __future__ import annotations + +import json +from urllib.parse import parse_qs + +from gflow_cli.api.transports.frame_builder import build_ogiz0b_body + + +def _decode_body(body: str) -> tuple[str, list[object], str]: + form = parse_qs(body) + f_req_value = form["f.req"][0] + outer = json.loads(f_req_value) + rpcid, inner_json, _, _ = outer[0][0] + return rpcid, json.loads(inner_json), inner_json + + +def test_builds_proven_ogiz0b_wire_shape() -> None: + body = build_ogiz0b_body( + prompt="a fox", + model="IMAGEN", + project_id="project-123", + recaptcha_token="captcha-456", + at_token="at-789", + batch_id="batch-abc", + session_counter=12345, + ) + + form = parse_qs(body) + outer = json.loads(form["f.req"][0]) + assert len(outer) == 1 + assert len(outer[0]) == 1 + rpcid, inner_json, none_value, generic = outer[0][0] + assert rpcid == "ogiZ0b" + assert isinstance(inner_json, str) + assert none_value is None + assert generic == "generic" + assert form["at"] == ["at-789"] + + inner = json.loads(inner_json) + ctx = inner[3] + entry = inner[1][0] + assert len(ctx) == 11 + assert ctx[5] == "project-123" + assert ctx[10] == ["captcha-456", 1] + assert len(entry) == 12 + assert entry[3] == 12345 + assert entry[4] == 2 + assert entry[5] == "IMAGEN" + assert entry[8] == [[["a fox"]]] + assert inner[4] == ["batch-abc"] + assert entry[7] == ctx + assert entry[7] is not ctx + + +def test_build_is_deterministic_for_the_same_inputs() -> None: + values = { + "prompt": "a fox", + "model": "IMAGEN", + "project_id": "project-123", + "recaptcha_token": "captcha-456", + "at_token": "at-789", + "batch_id": "batch-abc", + "session_counter": 12345, + } + + assert build_ogiz0b_body(**values) == build_ogiz0b_body(**values) + + +def test_prompt_round_trips_through_form_and_compact_inner_json() -> None: + prompt = 'a "fox" & café\n' + body = build_ogiz0b_body( + prompt=prompt, + model="IMAGEN", + project_id="project-123", + recaptcha_token="captcha-456", + at_token="at-789", + batch_id="batch-abc", + session_counter=12345, + ) + + rpcid, inner, inner_json = _decode_body(body) + + assert rpcid == "ogiZ0b" + assert inner[1][0][8] == [[[prompt]]] + assert inner_json == json.dumps(inner, separators=(",", ":")) From c84c0321d0474c64a68ebf71287be27044d9b4af Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:16:42 +0000 Subject: [PATCH 06/32] Record transport telemetry fact and report map --- src/gflow_cli/api/_flow_generation.py | 4 ++++ src/gflow_cli/telemetry.py | 31 ++++++++++++++++++++++----- tests/api/test_client_image.py | 30 ++++++++++++++++++++++++++ tests/test_telemetry.py | 28 ++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 5 deletions(-) diff --git a/src/gflow_cli/api/_flow_generation.py b/src/gflow_cli/api/_flow_generation.py index 7347b6fe9..759a0ec94 100644 --- a/src/gflow_cli/api/_flow_generation.py +++ b/src/gflow_cli/api/_flow_generation.py @@ -15,6 +15,7 @@ import structlog +from gflow_cli import telemetry from gflow_cli.api import routes from gflow_cli.api._engine import ( mint_evaluate_kwargs, @@ -563,6 +564,9 @@ async def _drive_images_generation( "running the command again." ), ) from exc + telemetry.note_transport( + "direct" if any(img.transport == "direct_http" for img in images) else "ui" + ) if not images: raise ContentPolicyError( detail="empty media[]", diff --git a/src/gflow_cli/telemetry.py b/src/gflow_cli/telemetry.py index b9dce9692..e03667f74 100644 --- a/src/gflow_cli/telemetry.py +++ b/src/gflow_cli/telemetry.py @@ -450,6 +450,7 @@ def _connect(home: Path) -> sqlite3.Connection: _RUN_FACTS: ContextVar[dict[str, str] | None] = ContextVar("gflow_run_facts", default=None) _ENGINES = frozenset({"playwright", "patchright"}) _HOSTS = {"labs": "labs", "migrated": "flow"} +_TRANSPORTS = frozenset({"direct", "ui"}) def _facts() -> dict[str, str]: @@ -479,14 +480,26 @@ def note_host(kind: str | None) -> None: _facts()["host"] = _HOSTS[kind] +def note_transport(kind: str) -> None: + """Note the image transport used (closed enum: direct, ui; anything else is ``other``).""" + _facts()["transport"] = kind if kind in _TRANSPORTS else "other" + + def _take_run_facts() -> list[tuple[str, str]]: """The noted facts as counter keys, cleared so the next run starts empty.""" facts = _facts() noted = dict(facts) # snapshot, then clear: a concurrent clear cannot raise here facts.clear() # a host noted without a launch must not carry into a later run - if "engine" not in noted: + if "engine" not in noted and "transport" not in noted: return [] - return [("engine", noted["engine"]), ("host", noted.get("host", "unknown"))] + out: list[tuple[str, str]] = [] + if "engine" in noted: + out.append(("engine", noted["engine"])) + out.append(("host", noted.get("host", "unknown"))) + out.append(("transport", noted.get("transport", "unknown"))) + elif "transport" in noted: + out.append(("transport", noted["transport"])) + return out def flush_run_facts(surface: Literal["cli", "mcp"]) -> None: @@ -933,6 +946,7 @@ def _report_counter_targets() -> dict[str, Any]: "mcp_clients": {}, "engines": {}, "hosts": {}, + "transports": {}, "tools": tools, "nested": {"flag": flags, "exit": exits, "duration": durations, "tool": tools}, } @@ -979,8 +993,15 @@ def _add_scalar_counter( elif kind == "crash": values = targets["crashes"].setdefault(surface, {}) values[key] = values.get(key, 0) + count - elif kind in ("client", "engine", "host"): - values = targets[{"client": "mcp_clients", "engine": "engines", "host": "hosts"}[kind]] + elif kind in ("client", "engine", "host", "transport"): + values = targets[ + { + "client": "mcp_clients", + "engine": "engines", + "host": "hosts", + "transport": "transports", + }[kind] + ] values[key] = values.get(key, 0) + count @@ -1105,5 +1126,5 @@ def build_report(week: str) -> dict[str, object]: "crashes": counters["crashes"], "tools": counters["tools"], # Sent only when non-empty: an endpoint older than #1326 rejects the keys. - **{k: counters[k] for k in ("engines", "hosts") if counters[k]}, + **{k: counters[k] for k in ("engines", "hosts", "transports") if counters[k]}, } diff --git a/tests/api/test_client_image.py b/tests/api/test_client_image.py index 73aa7f053..2a3f14626 100644 --- a/tests/api/test_client_image.py +++ b/tests/api/test_client_image.py @@ -24,6 +24,7 @@ import pytest import structlog +from gflow_cli import telemetry from gflow_cli.api.client import FlowApiClient, FlowApiError from gflow_cli.api.dto import GeneratedImage from gflow_cli.api.image import Aspect, GenerateImageRequest @@ -1015,3 +1016,32 @@ async def test_a_redirect_off_an_allowed_host_is_refused_and_nothing_is_written( _make_image(fife_url="https://flow.google.com/asb/opaque=s0"), out ) assert not out.exists() + + +class TestImageGenerationTransportTelemetry: + async def test_notes_direct_transport_when_image_has_direct_http( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + noted: list[str] = [] + monkeypatch.setattr(telemetry, "note_transport", noted.append) + img = dataclasses.replace(_make_image(), transport="direct_http") + transport = _FakeTransport([img]) + client = _client_with_transport(tmp_path, transport) + + await client.generate_image(project_id="proj-1", req=_make_req()) + + assert noted == ["direct"] + + async def test_notes_ui_transport_when_image_has_no_transport( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + noted: list[str] = [] + monkeypatch.setattr(telemetry, "note_transport", noted.append) + img = _make_image() + assert img.transport is None + transport = _FakeTransport([img]) + client = _client_with_transport(tmp_path, transport) + + await client.generate_image(project_id="proj-1", req=_make_req()) + + assert noted == ["ui"] diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 18933ee3d..2a2e7cdbd 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -333,6 +333,34 @@ def test_an_engine_outside_the_enum_is_other_and_facts_reset_per_command(tmp_hom assert report["hosts"] == {"labs": 1} +def test_a_transport_run_counts_its_transport_once(tmp_home: Path) -> None: + telemetry.note_transport("direct") + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"direct": 1} + + +def test_a_transport_ui_counts_ui(tmp_home: Path) -> None: + telemetry.note_transport("ui") + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"ui": 1} + + +def test_a_transport_outside_the_enum_is_other(tmp_home: Path) -> None: + telemetry.note_transport("custom-grpc") + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"other": 1} + + +def test_a_launch_that_noted_no_transport_counts_unknown(tmp_home: Path) -> None: + telemetry.note_engine("playwright") + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"unknown": 1} + + def test_the_worker_flushes_a_queued_job_s_facts(tmp_home: Path) -> None: telemetry.note_engine("playwright") telemetry.note_host("migrated") From b1d8023d6cc4920c914fbc763db785e880e3c433 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:18:16 +0000 Subject: [PATCH 07/32] Extract ogiz0b_reply_images reply mapper from _mc_submit_observe --- .../api/transports/_mc_submit_observe.py | 93 ++++++++++--------- .../fixtures/migrated_composer_contract.json | 2 +- tests/api/transports/test_direct_http.py | 43 +++++++++ 3 files changed, 95 insertions(+), 43 deletions(-) diff --git a/src/gflow_cli/api/transports/_mc_submit_observe.py b/src/gflow_cli/api/transports/_mc_submit_observe.py index 5bb26b506..ea44e9f34 100644 --- a/src/gflow_cli/api/transports/_mc_submit_observe.py +++ b/src/gflow_cli/api/transports/_mc_submit_observe.py @@ -140,6 +140,56 @@ def on_request(raw_request: Any) -> None: return on_request, unguarded +def ogiz0b_reply_images(text: str, request: GenerateImageRequest) -> list[GeneratedImage]: + """Extract GeneratedImage DTOs from an ogiZ0b batchexecute response. + + Raises refusal exception (ContentPolicyError, WafRejectionError) if Flow refused the submit. + Raises WireFormatError if no ogiZ0b frame or records were returned. + """ + refusal = _submit_refusal(text, (IMAGE_SUBMIT_RPC,)) + if refusal is not None: + raise refusal + parsed = parse_frames(text) + records = [ + record + for rpcid, payload in parsed + if rpcid == IMAGE_SUBMIT_RPC + for record in image_records(rpcid, payload) + ] + if not records: + log.warning( + "migrated.image_submit_unparsed_reply", + rpcid=IMAGE_SUBMIT_RPC, + text_len=len(text), + parsed_count=len(parsed), + parsed_rpcids=[p[0] for p in parsed], + ) + raise WireFormatError( + detail="migrated image submit returned no ogiZ0b frame", + route=f"batchexecute:{IMAGE_SUBMIT_RPC}", + ) + return [ + GeneratedImage( + media_name=record.media_id, + workflow_id=record.workflow_id, + seed=record.seed, + prompt=record.prompt, + # #789: the ogiZ0b reply carries no model field. Echoing + # the request back would report an attribution this host + # never confirmed — and with a hidden model picker (#788) + # the selected model can differ from the requested one, + # making the echo actively wrong on the single field a + # user would check to find out. + model_name_type=None, + aspect_ratio=request.aspect.value, + fife_url=record.image_url, + dimensions=record.dimensions, + display_name=record.display_name, + ) + for record in records + ] + + class SubmitObserveMixin(MentionMixin): """Prompt sending, generation submission, response polling and observation.""" @@ -781,48 +831,7 @@ async def on_response(response: Any) -> None: body_lost.set_result(None) return try: - refusal = _submit_refusal(text, (IMAGE_SUBMIT_RPC,)) - if refusal is not None: - raise refusal - parsed = parse_frames(text) - records = [ - record - for rpcid, payload in parsed - if rpcid == IMAGE_SUBMIT_RPC - for record in image_records(rpcid, payload) - ] - if not records: - log.warning( - "migrated.image_submit_unparsed_reply", - rpcid=IMAGE_SUBMIT_RPC, - text_len=len(text), - parsed_count=len(parsed), - parsed_rpcids=[p[0] for p in parsed], - ) - raise WireFormatError( - detail="migrated image submit returned no ogiZ0b frame", - route=f"batchexecute:{IMAGE_SUBMIT_RPC}", - ) - images = [ - GeneratedImage( - media_name=record.media_id, - workflow_id=record.workflow_id, - seed=record.seed, - prompt=record.prompt, - # #789: the ogiZ0b reply carries no model field. Echoing - # the request back would report an attribution this host - # never confirmed — and with a hidden model picker (#788) - # the selected model can differ from the requested one, - # making the echo actively wrong on the single field a - # user would check to find out. - model_name_type=None, - aspect_ratio=request.aspect.value, - fife_url=record.image_url, - dimensions=record.dimensions, - display_name=record.display_name, - ) - for record in records - ] + images = ogiz0b_reply_images(text, request) except Exception as exc: # noqa: BLE001 - delivered through the waiting future result.set_exception(exc) return diff --git a/tests/api/transports/fixtures/migrated_composer_contract.json b/tests/api/transports/fixtures/migrated_composer_contract.json index 1cf2c492d..116f48174 100644 --- a/tests/api/transports/fixtures/migrated_composer_contract.json +++ b/tests/api/transports/fixtures/migrated_composer_contract.json @@ -50,7 +50,7 @@ "reference_existing": "function (self, page: 'Page', project_id: 'str', request: 'GenerateImageRequest', *, name_resolver: 'Callable[[str], str | None] | None' = None) -> 'tuple[str, ...]' sha=8fb9a1d97c81eba0", "send_prompt": "function (self, page: 'Page', prompt: 'str', *, append: 'bool' = False) -> 'None' sha=da72d766802c433e", "submit_and_observe": "function (self, page: 'Page', *, poll_timeout_s: 'float', on_started: 'VideoStartedCallback | None', project_id: 'str | None', expect_media_id: 'str | None' = None, expect_end_media_id: 'str | None' = None, expect_reference_ids: 'tuple[str, ...]' = (), submit_rpcs: 'tuple[str, ...]' = ('YhhmEf', 'eb1hJf', 'MZZa6b', 'nprQif'), submit_selector: 'str | None' = None, request_check: 'Callable[[str, str], GFlowError | None] | None' = None, adopt_ids: 'tuple[str, ...]' = (), adopt_prompt: 'str | None' = None) -> 'GenerationRecord' sha=23505c9d43fcaa64", - "submit_images_and_observe": "function (self, page: 'Page', request: 'GenerateImageRequest', *, reference_ids: 'tuple[str, ...]' = (), entity_ids: 'tuple[str, ...]' = ()) -> 'list[GeneratedImage]' sha=5f35c8fcd5570dc2", + "submit_images_and_observe": "function (self, page: 'Page', request: 'GenerateImageRequest', *, reference_ids: 'tuple[str, ...]' = (), entity_ids: 'tuple[str, ...]' = ()) -> 'list[GeneratedImage]' sha=3fa86bdd9665e91b", "upload": "function (self, page: 'Page', project_id: 'str', image_path: 'Path') -> 'tuple[str, str]' sha=f33460601b0af4b8" }, "module_names": { diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 86801f05d..1815e947c 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -1,11 +1,17 @@ from __future__ import annotations +import json from pathlib import Path import pytest +from gflow_cli.api.dto import GeneratedImage from gflow_cli.api.image import AgentInstruction, Aspect, GenerateImageRequest, ImageRef +from gflow_cli.api.transports._mc_common import UNUSUAL_ACTIVITY_REASON +from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images from gflow_cli.api.transports.direct_http import direct_can_serve +from gflow_cli.errors import WafRejectionError, WireFormatError +from tests.api.transports.test_migrated_images import MEDIA, URL, WORKFLOW, image_payload def test_direct_can_serve_plain_t2i() -> None: @@ -30,3 +36,40 @@ def test_direct_can_serve_excluded_shapes(kwargs: dict[str, object]) -> None: base = {"prompt": "A cinematic view of mountains"} req = GenerateImageRequest(**{**base, **kwargs}) assert direct_can_serve(req) is False + + +def test_ogiz0b_reply_images_success() -> None: + payload = image_payload() + frame_json = json.dumps( + [["wrb.fr", "ogiZ0b", json.dumps(payload), None, None, None, "generic"]] + ) + text = f")]}}'\n{frame_json}" + req = GenerateImageRequest(prompt="a blue cup") + images = ogiz0b_reply_images(text, req) + assert len(images) == 1 + img = images[0] + assert isinstance(img, GeneratedImage) + assert img.media_name == MEDIA + assert img.workflow_id == WORKFLOW + assert img.prompt == "a blue cup" + assert img.seed == 12345 + assert img.aspect_ratio == Aspect.PORTRAIT.value + assert img.dimensions == (1376, 768) + assert img.display_name == "Blue cup" + assert img.fife_url == URL + + +def test_ogiz0b_reply_images_no_frame() -> None: + req = GenerateImageRequest(prompt="a blue cup") + with pytest.raises(WireFormatError, match="migrated image submit returned no ogiZ0b frame"): + ogiz0b_reply_images(")]}'\n", req) + + +def test_ogiz0b_reply_images_refusal() -> None: + req = GenerateImageRequest(prompt="a blue cup") + err_body = json.dumps( + [["wrb.fr", "ogiZ0b", None, None, None, [3, None, [[UNUSUAL_ACTIVITY_REASON]]], "generic"]] + ) + text = f")]}}'\n{err_body}" + with pytest.raises(WafRejectionError): + ogiz0b_reply_images(text, req) From a5966b4c08b4cfdcd79dd3db36c093b17cfa31f0 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:25:38 +0000 Subject: [PATCH 08/32] Bump notice version to 4, name transport in notice and docs --- CHANGELOG.md | 4 ++++ docs/TELEMETRY.md | 15 ++++++++------- src/gflow_cli/telemetry.py | 21 +++++++++------------ tests/test_telemetry.py | 4 ++-- tests/test_telemetry_notice.py | 14 ++++++++++++++ website/docs/TELEMETRY.md | 15 ++++++++------- 6 files changed, 45 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 391b4b872..c5e1611c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **The weekly usage report counts the image transport used.** A new field, `transports` (`direct`, `ui`, `other`, `unknown`), counts image generations by transport strategy (`direct` for direct HTTP, `ui` for UI automation, or `unknown` when none was noted), and generated asset metadata records `"transport": "direct_http"` when direct transport produced the image. The privacy notice moves to version 4 and names image transport. In the EU and EEA, consent given to an earlier notice version no longer counts: uploads stop until `gflow telemetry on` is run again. + ### Fixed - **A new-project button that will not take the click on `flow.google.com` is exit 23, not a crash ([#1434](https://github.com/ffroliva/gflow-cli/issues/1434)).** Generating without `--project` creates a project first. When the projects page's button rendered but the click timed out, Playwright's timeout escaped as an unhandled error (exit 1). gflow now checks whether the create request left the page: if it did not, the run stops with exit 23 and `charged: no`, saying no create request was sent and suggesting `--project` (MCP `project`); if it did, Flow may have made the project, so gflow waits for Flow's reply or reads the new project back, and reports exit 7 (not retryable) only if neither confirms it. diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 83eecc120..1b2af0599 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -10,7 +10,7 @@ Counters are kept in `/telemetry.db`, separately from the catalo grouped by ISO week and retained for 53 weeks. gflow counts command and flag names, outcomes, coarse duration buckets, command transitions, crash fingerprints made from exception and code names, and generation details read from the local catalog. It also records the storage service category and MCP -client category, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. +client category, image transport, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. `gflow telemetry show` prints the current week's report as JSON, including its random per-week `report_id`; this is the report sent by the uploader. `gflow data stats` shows your own local usage @@ -35,6 +35,7 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | +| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. Runs that noted no transport count as `unknown`. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent @@ -82,7 +83,7 @@ read your IP address or locale to make this decision, and never sends the timezo Local counters still work in the EU/EEA and remain on your device unless you consent. To allow weekly uploads, run `gflow telemetry on`; this records your choice locally in `/telemetry.consent`, together with the notice version you agreed to. When the -notice changes (version 3 added the browser engine and the Flow site), uploads stop until you run +notice changes (version 4 added image transport), uploads stop until you run `gflow telemetry on` again. Run `gflow telemetry off` to withdraw consent and stop counting and uploads. Environment kill switches still take precedence. @@ -119,13 +120,13 @@ the sender is `src/gflow_cli/telemetry_upload.py` in this repository. ## Notice -Notice version: 3 +Notice version: 4 ```text gflow sends weekly usage totals to improve it, and we share overall figures publicly and with -sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and -your country as a total. No ID, prompts, paths or account details. Each report is added to -totals and discarded. +sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, +error codes, and your country as a total. No ID, prompts, paths or account details. Each +report is added to totals and discarded. Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0 See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` @@ -133,7 +134,7 @@ See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETR The notice shown in the EU/EEA: ```text -gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. +gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry off) See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` diff --git a/src/gflow_cli/telemetry.py b/src/gflow_cli/telemetry.py index e03667f74..a01db3135 100644 --- a/src/gflow_cli/telemetry.py +++ b/src/gflow_cli/telemetry.py @@ -53,22 +53,22 @@ def _debug(event: str, **kw: str) -> None: OFF_FILE = "telemetry.off" CONSENT_FILE = "telemetry.consent" SCHEMA = 1 -NOTICE_VERSION = 3 +NOTICE_VERSION = 4 NOTICE_TEXT = ( "gflow sends weekly usage totals to improve it, and we share overall figures publicly and " "with\n" - "sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and\n" - "your country as a total. No ID, prompts, paths or account details. Each report is added to\n" - "totals and discarded.\n" + "sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used,\n" + "error codes, and your country as a total. No ID, prompts, paths or account details. Each\n" + "report is added to totals and discarded.\n" "Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0\n" "See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY" ) NOTICE_TEXT_CONSENT = ( "gflow can send weekly usage totals to help improve it; overall figures are shared publicly " "and " - "with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, " - "and your country as a total. No ID, prompts, paths or account details. Each report is " - "added to totals and discarded.\n" + "with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site " + "used, error codes, and your country as a total. No ID, prompts, paths or account details. " + "Each report is added to totals and discarded.\n" "In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry " "off)\n" "See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY" @@ -450,7 +450,7 @@ def _connect(home: Path) -> sqlite3.Connection: _RUN_FACTS: ContextVar[dict[str, str] | None] = ContextVar("gflow_run_facts", default=None) _ENGINES = frozenset({"playwright", "patchright"}) _HOSTS = {"labs": "labs", "migrated": "flow"} -_TRANSPORTS = frozenset({"direct", "ui"}) +_TRANSPORTS = frozenset({"direct", "ui", "unknown"}) def _facts() -> dict[str, str]: @@ -490,14 +490,11 @@ def _take_run_facts() -> list[tuple[str, str]]: facts = _facts() noted = dict(facts) # snapshot, then clear: a concurrent clear cannot raise here facts.clear() # a host noted without a launch must not carry into a later run - if "engine" not in noted and "transport" not in noted: - return [] out: list[tuple[str, str]] = [] if "engine" in noted: out.append(("engine", noted["engine"])) out.append(("host", noted.get("host", "unknown"))) - out.append(("transport", noted.get("transport", "unknown"))) - elif "transport" in noted: + if "transport" in noted: out.append(("transport", noted["transport"])) return out diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 2a2e7cdbd..212ab7ea9 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -354,8 +354,8 @@ def test_a_transport_outside_the_enum_is_other(tmp_home: Path) -> None: assert report["transports"] == {"other": 1} -def test_a_launch_that_noted_no_transport_counts_unknown(tmp_home: Path) -> None: - telemetry.note_engine("playwright") +def test_a_transport_unknown_counts_unknown(tmp_home: Path) -> None: + telemetry.note_transport("unknown") telemetry.record("cli", "image t2i", [], "0", 3.0) report = _report() assert report["transports"] == {"unknown": 1} diff --git a/tests/test_telemetry_notice.py b/tests/test_telemetry_notice.py index 20fe304fe..55b0f6789 100644 --- a/tests/test_telemetry_notice.py +++ b/tests/test_telemetry_notice.py @@ -511,3 +511,17 @@ def test_consent_to_an_earlier_notice_is_not_consent( assert telemetry.consent_at() is None # v2 wrote a bare timestamp telemetry.set_consent() assert telemetry.consent_at() is not None + + +def test_consent_to_v3_notice_is_not_consent_for_v4( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A v3 consent must be renewed now that notice v4 names image transport.""" + home = tmp_path / "gflow_home" + home.mkdir(exist_ok=True) + monkeypatch.setenv("GFLOW_CLI_HOME", str(home)) + monkeypatch.setattr(telemetry, "consent_region", lambda: True) + (home / telemetry.CONSENT_FILE).write_text("2026-11-01T00:00:00+00:00\n3", encoding="utf-8") + assert telemetry.consent_at() is None + telemetry.set_consent() + assert telemetry.consent_at() is not None diff --git a/website/docs/TELEMETRY.md b/website/docs/TELEMETRY.md index cf689fe5f..3c0637d48 100644 --- a/website/docs/TELEMETRY.md +++ b/website/docs/TELEMETRY.md @@ -10,7 +10,7 @@ Counters are kept in `/telemetry.db`, separately from the catalo grouped by ISO week and retained for 53 weeks. gflow counts command and flag names, outcomes, coarse duration buckets, command transitions, crash fingerprints made from exception and code names, and generation details read from the local catalog. It also records the storage service category and MCP -client category, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. +client category, image transport, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. `gflow telemetry show` prints the current week's report as JSON, including its random per-week `report_id`; this is the report sent by the uploader. `gflow data stats` shows your own local usage @@ -35,6 +35,7 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | +| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. Runs that noted no transport count as `unknown`. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent @@ -82,7 +83,7 @@ read your IP address or locale to make this decision, and never sends the timezo Local counters still work in the EU/EEA and remain on your device unless you consent. To allow weekly uploads, run `gflow telemetry on`; this records your choice locally in `/telemetry.consent`, together with the notice version you agreed to. When the -notice changes (version 3 added the browser engine and the Flow site), uploads stop until you run +notice changes (version 4 added image transport), uploads stop until you run `gflow telemetry on` again. Run `gflow telemetry off` to withdraw consent and stop counting and uploads. Environment kill switches still take precedence. @@ -119,13 +120,13 @@ the sender is `src/gflow_cli/telemetry_upload.py` in this repository. ## Notice -Notice version: 3 +Notice version: 4 ```text gflow sends weekly usage totals to improve it, and we share overall figures publicly and with -sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and -your country as a total. No ID, prompts, paths or account details. Each report is added to -totals and discarded. +sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, +error codes, and your country as a total. No ID, prompts, paths or account details. Each +report is added to totals and discarded. Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0 See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` @@ -133,7 +134,7 @@ See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETR The notice shown in the EU/EEA: ```text -gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. +gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry off) See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` From 0fc2fe7e84c01c61baaa39ebaff223420bb55d8f Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:29:52 +0000 Subject: [PATCH 09/32] Implement DirectHttpTransport with fallback and direct HTTP runner --- src/gflow_cli/api/flow_wire.py | 4 + src/gflow_cli/api/transports/direct_http.py | 293 +++++++++- tests/api/transports/test_direct_http.py | 584 +++++++++++++++++++- 3 files changed, 878 insertions(+), 3 deletions(-) diff --git a/src/gflow_cli/api/flow_wire.py b/src/gflow_cli/api/flow_wire.py index 3127dccef..7a921fa96 100644 --- a/src/gflow_cli/api/flow_wire.py +++ b/src/gflow_cli/api/flow_wire.py @@ -242,6 +242,7 @@ def _rpc_request( build_rpc_request = _rpc_request +user_agent = _user_agent async def _shell_tokens( @@ -270,6 +271,9 @@ async def _shell_tokens( return tokens +shell_tokens = _shell_tokens + + async def _read_cookies(profile_dir: Path) -> list[tuple[str, str]]: """``read_cookies_for`` on a daemon thread, bounded by ``_TOTAL_S``. diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 3dced2ade..5d25ab70a 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -2,13 +2,39 @@ from __future__ import annotations -from typing import TYPE_CHECKING +import secrets +import time +import uuid +from collections.abc import Callable +from dataclasses import replace +from http.cookiejar import CookieJar, DefaultCookiePolicy +from typing import TYPE_CHECKING, Any +from urllib.parse import urlencode +import httpx +import structlog + +from gflow_cli.api import flow_wire +from gflow_cli.api._engine import mint_evaluate_kwargs from gflow_cli.api.image import Aspect +from gflow_cli.api.recaptcha import TokenMinter +from gflow_cli.api.transports._common import migrated_route +from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images +from gflow_cli.api.transports.frame_builder import build_ogiz0b_body +from gflow_cli.api.transports.ui_automation import UiAutomationTransport +from gflow_cli.config import get_settings +from gflow_cli.errors import NetworkError if TYPE_CHECKING: + from pathlib import Path + + from playwright.async_api import Page + + from gflow_cli.api.dto import GeneratedImage from gflow_cli.api.image import GenerateImageRequest +log = structlog.get_logger(__name__) + def direct_can_serve(request: GenerateImageRequest) -> bool: """Return True only for plain T2I requests supported by direct HTTP. @@ -28,3 +54,268 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: if "@" in request.prompt: return False return True + + +class _DirectFallbackError(Exception): + """Internal sentinel indicating the direct path should fall back to UI automation.""" + + def __init__(self, reason: str) -> None: + super().__init__(reason) + self.reason = reason + + +class DirectImageHttpRunner: + """Collaborator executing the direct HTTP sequence for image generation. + + Coordinates live cookies, shell tokens, page minting, ogiZ0b frame building, + batchexecute POST, and response parsing. + """ + + def __init__(self, *, http_transport: httpx.AsyncBaseTransport | None = None) -> None: + self._http_transport = http_transport + + async def run( + self, + *, + page: Page, + profile_dir: Path, + project_id: str, + request: GenerateImageRequest, + ) -> list[GeneratedImage]: + t_start = time.perf_counter() + + # 1. Read live cookies from browser context + try: + cookie_list = await page.context.cookies(["https://flow.google.com"]) + cookie_parts = [ + f"{name}={value}" + for c in cookie_list + if (name := c.get("name")) and (value := c.get("value")) + ] + cookie_header = "; ".join(cookie_parts) + if not cookie_header: + raise _DirectFallbackError("cookies_empty") + except _DirectFallbackError: + raise + except Exception as exc: + raise _DirectFallbackError(f"cookie_error:{type(exc).__name__}") from exc + + # 2. Shell headers and user agent + ua = flow_wire.user_agent(profile_dir) + headers = { + "accept-language": "en-US,en;q=0.9", + "cookie": cookie_header, + } + if ua: + headers["user-agent"] = ua + + client_kwargs: dict[str, Any] = { + "follow_redirects": False, + "trust_env": False, + "timeout": httpx.Timeout(120.0, connect=10.0), + "cookies": CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])), + } + if self._http_transport is not None: + client_kwargs["transport"] = self._http_transport + + async with httpx.AsyncClient(**client_kwargs) as client: + # 3. Shell tokens + try: + tokens = await flow_wire.shell_tokens(client, profile_dir, headers) + except flow_wire.WireReadUnavailable as exc: + raise _DirectFallbackError(exc.reason.value) from exc + except Exception as exc: + raise _DirectFallbackError(f"shell_tokens:{type(exc).__name__}") from exc + + # 4. Page navigation check & reCAPTCHA token minting + target_url = f"https://flow.google.com/project/{project_id}" + if not page.url.startswith(target_url): + try: + await page.goto(target_url) + except Exception as exc: + raise _DirectFallbackError(f"navigation_failed:{type(exc).__name__}") from exc + + mint_start = time.perf_counter() + try: + token = await TokenMinter(page, mint_evaluate_kwargs=mint_evaluate_kwargs()).mint( + "IMAGE_GENERATION" + ) + except Exception as exc: + raise _DirectFallbackError("mint_failure") from exc + mint_ms = int((time.perf_counter() - mint_start) * 1000) + + # 5. Build ogiZ0b body + batch_id = str(uuid.uuid4()).upper() + session_counter = 1 + secrets.randbelow(2**31 - 1) + body = build_ogiz0b_body( + prompt=request.prompt, + model=request.model.value, + project_id=project_id, + recaptcha_token=token, + at_token=tokens.at, + batch_id=batch_id, + session_counter=session_counter, + ) + log.info( + "direct.frame_built", + model=request.model.value, + prompt_length=len(request.prompt), + ) + + # 6. POST + query = { + "rpcids": "ogiZ0b", + "source-path": f"/project/{project_id}", + "bl": tokens.bl, + "f.sid": tokens.fsid, + "hl": "en", + "_reqid": str(1000 + secrets.randbelow(9000)), + "rt": "c", + } + post_url = ( + f"https://flow.google.com/_/AiSandboxAngularFrontend/data/batchexecute?" + f"{urlencode({k: v for k, v in query.items() if v is not None})}" + ) + post_headers = { + **headers, + "content-type": "application/x-www-form-urlencoded;charset=UTF-8", + "x-same-domain": "1", + "origin": "https://flow.google.com", + "referer": f"https://flow.google.com/project/{project_id}", + "sec-fetch-site": "same-origin", + "sec-fetch-mode": "cors", + "sec-fetch-dest": "empty", + } + + post_start = time.perf_counter() + try: + response = await client.post(post_url, content=body, headers=post_headers) + except httpx.ConnectError as exc: + raise _DirectFallbackError("connect_error") from exc + except (httpx.TimeoutException, httpx.TransportError) as exc: + cause = (str(exc).strip().splitlines() or [""])[0][:160] + raise NetworkError( + detail=f"{type(exc).__name__} on an image submit ({cause}); not resent", + route="batchexecute:ogiZ0b", + next_action="reconcile", + remediation_hint=( + "Flow may have accepted this image request before the error, so gflow " + "did not resend it. Check the project in Flow for the new image before " + "running the command again." + ), + ) from exc + + post_ms = int((time.perf_counter() - post_start) * 1000) + total_ms = int((time.perf_counter() - t_start) * 1000) + log.info( + "direct.image_post", + status=response.status_code, + mint_ms=mint_ms, + post_ms=post_ms, + total_ms=total_ms, + ) + + if response.status_code == 403: + raise _DirectFallbackError("http_403") + + if response.status_code != 200: + raise NetworkError( + detail=f"HTTP {response.status_code} on an image submit; not resent", + status=response.status_code, + route="batchexecute:ogiZ0b", + next_action="reconcile", + remediation_hint=( + "Flow may have accepted this image request before the error, so gflow " + "did not resend it. Check the project in Flow for the new image before " + "running the command again." + ), + ) + + images = ogiz0b_reply_images(response.text, request) + return [replace(img, transport="direct_http") for img in images] + + +class DirectHttpTransport(UiAutomationTransport): + """Direct HTTP transport for image generation with reCAPTCHA minting from Flow page.""" + + name = "direct_http" + _profile_dir: Path | None = None + + def __init__( + self, + *, + http_transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + super().__init__() + self._http_transport = http_transport + self._runner = DirectImageHttpRunner(http_transport=http_transport) + + async def setup(self, profile_dir: Path, *, page: Page | None = None) -> None: + self._profile_dir = profile_dir + await super().setup(profile_dir, page=page) + + async def generate_images( + self, + *, + project_id: str | None, + request: GenerateImageRequest, + name_resolver: Callable[[str], str | None] | None = None, + ) -> list[GeneratedImage]: + """Generate images via direct HTTP when eligible, falling back to UI automation.""" + if not self._setup_done or self._page is None: + msg = "DirectHttpTransport.setup() must be called before generate_images()" + raise RuntimeError(msg) + + async with self._generate_lock: + await self.park_deferred_page() + + if not direct_can_serve(request): + log.info("direct.fallback_to_ui", reason="unsupported_shape") + return await self._generate_images_locked( + request, project_id=project_id, name_resolver=name_resolver + ) + + if project_id is None: + log.info("direct.fallback_to_ui", reason="no_project") + return await self._generate_images_locked( + request, project_id=project_id, name_resolver=name_resolver + ) + + page = self._page + profile_dir = self._profile_dir + if profile_dir is None: + log.info("direct.fallback_to_ui", reason="no_profile_dir") + return await self._generate_images_locked( + request, project_id=project_id, name_resolver=name_resolver + ) + + flow_host = get_settings().flow_host + route = migrated_route(page.url, flow_host, prefer_migrated=True) + if route != "migrated": + log.info("direct.fallback_to_ui", reason="route_not_migrated") + return await self._generate_images_locked( + request, project_id=project_id, name_resolver=name_resolver + ) + + if get_settings().browser_proxy or flow_wire.getproxies(): + log.info("direct.fallback_to_ui", reason="proxy_configured") + return await self._generate_images_locked( + request, project_id=project_id, name_resolver=name_resolver + ) + + runner = DirectImageHttpRunner(http_transport=self._http_transport) + + try: + images = await runner.run( + page=page, + profile_dir=profile_dir, + project_id=project_id, + request=request, + ) + self.last_image_route = "migrated" + return images + except _DirectFallbackError as fb: + log.info("direct.fallback_to_ui", reason=fb.reason) + return await self._generate_images_locked( + request, project_id=project_id, name_resolver=name_resolver + ) diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 1815e947c..591e5809b 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -2,18 +2,31 @@ import json from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, MagicMock +import httpx import pytest +from gflow_cli.api import flow_wire from gflow_cli.api.dto import GeneratedImage from gflow_cli.api.image import AgentInstruction, Aspect, GenerateImageRequest, ImageRef from gflow_cli.api.transports._mc_common import UNUSUAL_ACTIVITY_REASON from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images -from gflow_cli.api.transports.direct_http import direct_can_serve -from gflow_cli.errors import WafRejectionError, WireFormatError +from gflow_cli.api.transports.direct_http import DirectHttpTransport, direct_can_serve +from gflow_cli.config import get_settings +from gflow_cli.errors import NetworkError, WafRejectionError, WireFormatError from tests.api.transports.test_migrated_images import MEDIA, URL, WORKFLOW, image_payload +@pytest.fixture(autouse=True) +def _clean_flow_wire(monkeypatch: pytest.MonkeyPatch) -> Any: + flow_wire.reset_state() + monkeypatch.setattr(flow_wire, "getproxies", dict) + yield + flow_wire.reset_state() + + def test_direct_can_serve_plain_t2i() -> None: req = GenerateImageRequest(prompt="A cinematic view of mountains") assert direct_can_serve(req) is True @@ -73,3 +86,570 @@ def test_ogiz0b_reply_images_refusal() -> None: text = f")]}}'\n{err_body}" with pytest.raises(WafRejectionError): ogiz0b_reply_images(text, req) + + +def _valid_ogiz0b_text() -> str: + payload = image_payload() + frame_json = json.dumps( + [["wrb.fr", "ogiZ0b", json.dumps(payload), None, None, None, "generic"]] + ) + return f")]}}'\n{frame_json}" + + +def _make_fake_page(url: str = "https://flow.google.com/project/proj-123") -> MagicMock: + page = MagicMock() + page.url = url + page.goto = AsyncMock() + page.context = MagicMock() + page.context.cookies = AsyncMock(return_value=[{"name": "SID", "value": "test_sid"}]) + return page + + +@pytest.fixture +def mock_mint_and_body(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", + AsyncMock(return_value="mock_token"), + ) + monkeypatch.setattr( + "gflow_cli.api.transports.frame_builder.build_ogiz0b_body", + MagicMock(return_value="f.req=mock_body&at=at-x&"), + ) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.build_ogiz0b_body", + MagicMock(return_value="f.req=mock_body&at=at-x&"), + ) + + +@pytest.fixture +def transport(tmp_path: Path) -> DirectHttpTransport: + t = DirectHttpTransport() + t._setup_done = True + t._profile_dir = tmp_path + t._page = _make_fake_page() + t.park_deferred_page = AsyncMock() # type: ignore[method-assign] + return t + + +@pytest.mark.asyncio +async def test_direct_http_happy_path( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + post_count = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal post_count + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + if request.method == "POST": + post_count += 1 + return httpx.Response(200, text=_valid_ogiz0b_text()) + return httpx.Response(404) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + images = await transport.generate_images(project_id="proj-123", request=req) + + assert len(images) == 1 + assert images[0].transport == "direct_http" + assert transport.last_image_route == "migrated" + assert not ui_called + assert post_count == 1 + + +@pytest.mark.asyncio +async def test_direct_http_unsupported_shape_falls_back_to_ui( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + post_count = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal post_count + if request.method == "POST": + post_count += 1 + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup", count=2) + await transport.generate_images(project_id="proj-123", request=req) + + assert ui_called + assert post_count == 0 + + +@pytest.mark.asyncio +async def test_direct_http_pre_send_cookie_failure_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + transport._page.context.cookies = AsyncMock(side_effect=RuntimeError("cookie unreadable")) + post_count = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal post_count + if request.method == "POST": + post_count += 1 + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + + assert ui_called + assert post_count == 0 + + +@pytest.mark.asyncio +async def test_direct_http_pre_send_shell_tokens_failure_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response(401, text="Unauthorized") + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_pre_send_mint_failure_falls_back( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", + AsyncMock(side_effect=RuntimeError("minting failed")), + ) + monkeypatch.setattr( + "gflow_cli.api.transports.frame_builder.build_ogiz0b_body", + MagicMock(return_value="f.req=mock_body&at=at-x&"), + ) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.build_ogiz0b_body", + MagicMock(return_value="f.req=mock_body&at=at-x&"), + ) + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_pre_send_connect_error_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + raise httpx.ConnectError("Connection refused") + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_post_403_falls_back_to_ui( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + post_count = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal post_count + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + if request.method == "POST": + post_count += 1 + return httpx.Response(403, text="Forbidden") + return httpx.Response(404) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + + assert ui_called + assert post_count == 1 + + +@pytest.mark.asyncio +async def test_direct_http_post_500_raises_network_error( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + post_count = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal post_count + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + if request.method == "POST": + post_count += 1 + return httpx.Response(500, text="Internal Server Error") + return httpx.Response(404) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + with pytest.raises(NetworkError) as exc_info: + await transport.generate_images(project_id="proj-123", request=req) + + assert exc_info.value.next_action == "reconcile" + assert "not resent" in exc_info.value.detail + assert not ui_called + assert post_count == 1 + + +@pytest.mark.asyncio +async def test_direct_http_post_timeout_raises_network_error( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + post_count = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal post_count + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + if request.method == "POST": + post_count += 1 + raise httpx.ReadTimeout("Request timed out") + return httpx.Response(404) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + with pytest.raises(NetworkError) as exc_info: + await transport.generate_images(project_id="proj-123", request=req) + + assert exc_info.value.next_action == "reconcile" + assert "not resent" in exc_info.value.detail + assert not ui_called + assert post_count == 1 + + +@pytest.mark.asyncio +async def test_direct_http_setup_not_done_raises(transport: DirectHttpTransport) -> None: + transport._setup_done = False + req = GenerateImageRequest(prompt="a blue cup") + with pytest.raises(RuntimeError, match="setup.*must be called"): + await transport.generate_images(project_id="proj-123", request=req) + + +@pytest.mark.asyncio +async def test_direct_http_no_project_id_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id=None, request=req) + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_no_profile_dir_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + transport._profile_dir = None + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_route_not_migrated_falls_back( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, mock_mint_and_body: None +) -> None: + monkeypatch.setattr(get_settings(), "flow_host", "labs") + transport._page.url = "https://labs.google/fx/tools/flow" + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_proxy_configured_falls_back( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, mock_mint_and_body: None +) -> None: + monkeypatch.setattr(flow_wire, "getproxies", lambda: {"https": "http://127.0.0.1:8080"}) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_page_navigates_to_project_when_needed( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + transport._page.url = "https://flow.google.com/other" + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + transport._page.goto.assert_awaited_once_with("https://flow.google.com/project/proj-123") + + +@pytest.mark.asyncio +async def test_direct_http_navigation_error_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + transport._page.url = "https://flow.google.com/other" + transport._page.goto = AsyncMock(side_effect=RuntimeError("nav failed")) + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_post_transport_error_raises_network_error( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + if request.method == "POST": + raise httpx.ProtocolError("Protocol violation") + return httpx.Response(404) + + transport._http_transport = httpx.MockTransport(handler) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + + req = GenerateImageRequest(prompt="a blue cup") + with pytest.raises(NetworkError) as exc_info: + await transport.generate_images(project_id="proj-123", request=req) + + assert exc_info.value.next_action == "reconcile" + assert "not resent" in exc_info.value.detail + assert not ui_called + + +@pytest.mark.asyncio +async def test_direct_http_empty_cookies_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + transport._page.context.cookies = AsyncMock(return_value=[]) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_user_agent_included( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, mock_mint_and_body: None +) -> None: + monkeypatch.setattr(flow_wire, "user_agent", lambda _p: "CustomUA/1.0") + recorded_ua = None + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal recorded_ua + if request.method == "GET": + recorded_ua = request.headers.get("user-agent") + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + assert recorded_ua == "CustomUA/1.0" + + +@pytest.mark.asyncio +async def test_direct_http_shell_tokens_unexpected_error_falls_back( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, mock_mint_and_body: None +) -> None: + monkeypatch.setattr( + flow_wire, + "shell_tokens", + AsyncMock(side_effect=RuntimeError("unexpected shell error")), + ) + ui_called = False + + async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: + nonlocal ui_called + ui_called = True + return [] + + transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] + req = GenerateImageRequest(prompt="a blue cup") + await transport.generate_images(project_id="proj-123", request=req) + assert ui_called + + +@pytest.mark.asyncio +async def test_direct_http_setup_stores_profile_dir(tmp_path: Path) -> None: + t = DirectHttpTransport() + fake_page = _make_fake_page() + await t.setup(tmp_path, page=fake_page) + assert t._profile_dir == tmp_path + assert t._page is fake_page From 7f378cfcda002b517f9c701a6f9516653cda6984 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:31:03 +0000 Subject: [PATCH 10/32] fix(telemetry): keep the transport enum to the values a caller produces direct and ui only; anything else is counted as other. --- src/gflow_cli/telemetry.py | 2 +- tests/test_telemetry.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gflow_cli/telemetry.py b/src/gflow_cli/telemetry.py index a01db3135..ae4a3fbd4 100644 --- a/src/gflow_cli/telemetry.py +++ b/src/gflow_cli/telemetry.py @@ -450,7 +450,7 @@ def _connect(home: Path) -> sqlite3.Connection: _RUN_FACTS: ContextVar[dict[str, str] | None] = ContextVar("gflow_run_facts", default=None) _ENGINES = frozenset({"playwright", "patchright"}) _HOSTS = {"labs": "labs", "migrated": "flow"} -_TRANSPORTS = frozenset({"direct", "ui", "unknown"}) +_TRANSPORTS = frozenset({"direct", "ui"}) def _facts() -> dict[str, str]: diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 212ab7ea9..f8e87466d 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -354,11 +354,11 @@ def test_a_transport_outside_the_enum_is_other(tmp_home: Path) -> None: assert report["transports"] == {"other": 1} -def test_a_transport_unknown_counts_unknown(tmp_home: Path) -> None: - telemetry.note_transport("unknown") +def test_an_unlisted_transport_counts_other(tmp_home: Path) -> None: + telemetry.note_transport("direct_http") # a raw transport name never reaches the totals telemetry.record("cli", "image t2i", [], "0", 3.0) report = _report() - assert report["transports"] == {"unknown": 1} + assert report["transports"] == {"other": 1} def test_the_worker_flushes_a_queued_job_s_facts(tmp_home: Path) -> None: From 7ef67f34c464c6b502f1bc9bbc17068d1202b6e1 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:31:49 +0000 Subject: [PATCH 11/32] Register direct_http transport in experimental transports --- src/gflow_cli/api/transports/__init__.py | 3 +++ tests/api/transports/test_factory.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/gflow_cli/api/transports/__init__.py b/src/gflow_cli/api/transports/__init__.py index 571fa93f9..a80d9ad36 100644 --- a/src/gflow_cli/api/transports/__init__.py +++ b/src/gflow_cli/api/transports/__init__.py @@ -25,6 +25,7 @@ "evaluate_fetch", "bearer", "sapisidhash", + "direct_http", ) # Experimental transports whose ``setup()`` discards a caller-supplied ``page=`` @@ -41,6 +42,7 @@ def _registry() -> dict[str, type[FlowTransportStrategy]]: """Lazy registry import — keeps the factory cheap to import.""" + from gflow_cli.api.transports.direct_http import DirectHttpTransport from gflow_cli.api.transports.experimental.bearer import BearerTransport from gflow_cli.api.transports.experimental.evaluate_fetch import ( EvaluateFetchTransport, @@ -50,6 +52,7 @@ def _registry() -> dict[str, type[FlowTransportStrategy]]: return { "ui_automation": UiAutomationTransport, + "direct_http": DirectHttpTransport, "evaluate_fetch": EvaluateFetchTransport, "bearer": BearerTransport, "sapisidhash": SapisidhashTransport, diff --git a/tests/api/transports/test_factory.py b/tests/api/transports/test_factory.py index d2ffac221..aa1a207e9 100644 --- a/tests/api/transports/test_factory.py +++ b/tests/api/transports/test_factory.py @@ -84,3 +84,18 @@ def test_resolve_transport_name_precedence(monkeypatch): monkeypatch.setenv("GFLOW_CLI_TRANSPORT", "sapisidhash") assert resolve_transport_name() == "sapisidhash" assert resolve_transport_name("bearer") == "bearer" # explicit arg wins over env + + +def test_direct_http_registration() -> None: + from gflow_cli.api.transports import ( + EXPERIMENTAL_TRANSPORTS, + STANDALONE_ONLY_TRANSPORTS, + make_transport, + ) + from gflow_cli.api.transports.direct_http import DirectHttpTransport + + assert "direct_http" in EXPERIMENTAL_TRANSPORTS + assert "direct_http" not in STANDALONE_ONLY_TRANSPORTS + t = make_transport("direct_http") + assert isinstance(t, DirectHttpTransport) + assert t.name == "direct_http" From b8abd74cd9fbb96dc150b5d6eb483e2d11ebe221 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:33:05 +0000 Subject: [PATCH 12/32] Add offline BDD scenario for direct_http image transport --- tests/features/direct_http_transport.feature | 6 + .../test_direct_http_transport_steps.py | 119 ++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 tests/features/direct_http_transport.feature create mode 100644 tests/features/test_direct_http_transport_steps.py diff --git a/tests/features/direct_http_transport.feature b/tests/features/direct_http_transport.feature new file mode 100644 index 000000000..389d22f07 --- /dev/null +++ b/tests/features/direct_http_transport.feature @@ -0,0 +1,6 @@ +Feature: Direct HTTP transport for image generation on flow.google.com + + Scenario: Plain text-to-image uses direct HTTP transport + Given a profile served flow.google.com + When a plain text-to-image request runs on the direct_http transport + Then one direct POST is sent and the image is returned with transport direct_http diff --git a/tests/features/test_direct_http_transport_steps.py b/tests/features/test_direct_http_transport_steps.py new file mode 100644 index 000000000..0c05d764b --- /dev/null +++ b/tests/features/test_direct_http_transport_steps.py @@ -0,0 +1,119 @@ +"""Offline BDD step definitions for direct_http_transport.feature.""" + +from __future__ import annotations + +import asyncio +import json +from typing import TYPE_CHECKING, Any +from unittest.mock import AsyncMock, MagicMock + +import httpx +import pytest +from pytest_bdd import given, scenarios, then, when + +from gflow_cli.api import flow_wire +from gflow_cli.api.image import GenerateImageRequest +from gflow_cli.api.transports import make_transport +from gflow_cli.api.transports.direct_http import DirectHttpTransport +from tests.api.transports.test_migrated_images import image_payload + +if TYPE_CHECKING: + from pathlib import Path + +scenarios("direct_http_transport.feature") + + +def _valid_ogiz0b_text() -> str: + payload = image_payload() + frame_json = json.dumps( + [["wrb.fr", "ogiZ0b", json.dumps(payload), None, None, None, "generic"]] + ) + return f")]}}'\n{frame_json}" + + +@pytest.fixture(autouse=True) +def _clean_flow_wire(monkeypatch: pytest.MonkeyPatch) -> Any: + flow_wire.reset_state() + monkeypatch.setattr(flow_wire, "getproxies", dict) + yield + flow_wire.reset_state() + + +@pytest.fixture +def bdd_ctx() -> dict[str, Any]: + return {} + + +@given("a profile served flow.google.com") +def step_profile_served_flow( + bdd_ctx: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", + AsyncMock(return_value="mock_recaptcha_token"), + ) + monkeypatch.setattr( + "gflow_cli.api.transports.frame_builder.build_ogiz0b_body", + MagicMock(return_value="f.req=mock_body&at=at-x&"), + ) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.build_ogiz0b_body", + MagicMock(return_value="f.req=mock_body&at=at-x&"), + ) + + post_count = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal post_count + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + if request.method == "POST": + post_count += 1 + return httpx.Response(200, text=_valid_ogiz0b_text()) + return httpx.Response(404) + + mock_transport = httpx.MockTransport(handler) + + page = MagicMock() + page.url = "https://flow.google.com/project/proj-bdd-1" + page.goto = AsyncMock() + page.context = MagicMock() + page.context.cookies = AsyncMock(return_value=[{"name": "SID", "value": "test_sid"}]) + + t = make_transport("direct_http") + assert isinstance(t, DirectHttpTransport) + t._http_transport = mock_transport + t.park_deferred_page = AsyncMock() # type: ignore[method-assign] + + async def _init_transport() -> None: + await t.setup(tmp_path, page=page) + + asyncio.run(_init_transport()) + + bdd_ctx["transport"] = t + bdd_ctx["get_post_count"] = lambda: post_count + + +@when("a plain text-to-image request runs on the direct_http transport") +def step_run_t2i(bdd_ctx: dict[str, Any]) -> None: + t: DirectHttpTransport = bdd_ctx["transport"] + req = GenerateImageRequest(prompt="a cinematic sunset") + + async def _run() -> None: + bdd_ctx["images"] = await t.generate_images(project_id="proj-bdd-1", request=req) + + asyncio.run(_run()) + + +@then("one direct POST is sent and the image is returned with transport direct_http") +def step_verify_result(bdd_ctx: dict[str, Any]) -> None: + t: DirectHttpTransport = bdd_ctx["transport"] + images = bdd_ctx["images"] + get_post_count = bdd_ctx["get_post_count"] + + assert get_post_count() == 1 + assert len(images) == 1 + assert images[0].transport == "direct_http" + assert t.last_image_route == "migrated" From eebc85889c088353457ef47ee50f0f1e164e078f Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:38:21 +0000 Subject: [PATCH 13/32] fix(transport): send the migrated wire model name on the direct path NARWHAL is sent as BELUGA on flow.google.com, where Flow's catalogue no longer lists NARWHAL (#958). Models with no measured wire name route to the UI transport. Drops an unused runner instance. --- src/gflow_cli/api/transports/direct_http.py | 12 ++++++--- tests/api/transports/test_direct_http.py | 30 ++++++++++++++++++++- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 5d25ab70a..8b09aefbc 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -16,7 +16,7 @@ from gflow_cli.api import flow_wire from gflow_cli.api._engine import mint_evaluate_kwargs -from gflow_cli.api.image import Aspect +from gflow_cli.api.image import Aspect, Model from gflow_cli.api.recaptcha import TokenMinter from gflow_cli.api.transports._common import migrated_route from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images @@ -35,6 +35,11 @@ log = structlog.get_logger(__name__) +# The model name an ogiZ0b body carries on flow.google.com. Only BELUGA is measured (the +# page sends it for "Nano Banana 2.1", which replaced NARWHAL in Flow's catalogue, #958); +# every other model routes to the UI transport until its wire name is captured. +_WIRE_MODEL: dict[Model, str] = {Model.NARWHAL: "BELUGA"} + def direct_can_serve(request: GenerateImageRequest) -> bool: """Return True only for plain T2I requests supported by direct HTTP. @@ -43,7 +48,7 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: non-portrait aspect ratios, multi-image counts, Agent instructions, and character mentions (@). """ - if request.aspect is not Aspect.PORTRAIT: + if request.aspect is not Aspect.PORTRAIT or request.model not in _WIRE_MODEL: return False if request.count != 1: return False @@ -149,7 +154,7 @@ async def run( session_counter = 1 + secrets.randbelow(2**31 - 1) body = build_ogiz0b_body( prompt=request.prompt, - model=request.model.value, + model=_WIRE_MODEL[request.model], project_id=project_id, recaptcha_token=token, at_token=tokens.at, @@ -248,7 +253,6 @@ def __init__( ) -> None: super().__init__() self._http_transport = http_transport - self._runner = DirectImageHttpRunner(http_transport=http_transport) async def setup(self, profile_dir: Path, *, page: Page | None = None) -> None: self._profile_dir = profile_dir diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 591e5809b..a03d0ff69 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -10,7 +10,7 @@ from gflow_cli.api import flow_wire from gflow_cli.api.dto import GeneratedImage -from gflow_cli.api.image import AgentInstruction, Aspect, GenerateImageRequest, ImageRef +from gflow_cli.api.image import AgentInstruction, Aspect, GenerateImageRequest, ImageRef, Model from gflow_cli.api.transports._mc_common import UNUSUAL_ACTIVITY_REASON from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images from gflow_cli.api.transports.direct_http import DirectHttpTransport, direct_can_serve @@ -653,3 +653,31 @@ async def test_direct_http_setup_stores_profile_dir(tmp_path: Path) -> None: await t.setup(tmp_path, page=fake_page) assert t._profile_dir == tmp_path assert t._page is fake_page + + +@pytest.mark.asyncio +async def test_direct_http_sends_the_migrated_wire_model( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + """NARWHAL is sent as BELUGA on flow.google.com; Flow no longer lists NARWHAL (#958).""" + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + builder = MagicMock(return_value="f.req=mock_body&at=at-x&") + monkeypatch.setattr("gflow_cli.api.transports.direct_http.build_ogiz0b_body", builder) + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + await transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")) + assert builder.call_args.kwargs["model"] == "BELUGA" + + +@pytest.mark.parametrize("model", [m for m in Model if m is not Model.NARWHAL]) +def test_a_model_with_no_measured_migrated_wire_name_is_not_served(model: Model) -> None: + assert not direct_can_serve(GenerateImageRequest(prompt="x", model=model)) From aa271571e1ecf3badef3992bc8958a536429562a Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:41:21 +0000 Subject: [PATCH 14/32] test(e2e): a plain t2i on direct_http is made by one direct POST; 16:9 routes to the UI Two image runs (daily quota, zero credits). The catalog proves which transport made each image. --- tests/e2e/test_direct_image_e2e.py | 72 ++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 tests/e2e/test_direct_image_e2e.py diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py new file mode 100644 index 000000000..5b8b653bb --- /dev/null +++ b/tests/e2e/test_direct_image_e2e.py @@ -0,0 +1,72 @@ +"""Live E2E for the direct_http image transport (T1.6). + +A plain text-to-image run on ``GFLOW_CLI_TRANSPORT=direct_http`` is generated by one +direct ``ogiZ0b`` POST and recorded with ``metadata_json.transport = "direct_http"``; a +shape the direct path does not serve (16:9) is routed to the UI transport before any +POST and still generates. Both are image runs: daily quota, zero credits. + +Opt in with: + GFLOW_CLI_E2E_PROFILE= uv run pytest -m e2e_image -v \\ + tests/e2e/test_direct_image_e2e.py +""" + +from __future__ import annotations + +import json +import sqlite3 +import subprocess +import sys +from typing import TYPE_CHECKING + +import pytest + +from tests.e2e._redacted_env import RedactedEnv + +if TYPE_CHECKING: + from pathlib import Path + +pytestmark = [pytest.mark.e2e, pytest.mark.e2e_image] + +_JPEG_OR_PNG = (b"\xff\xd8\xff", b"\x89PNG\r\n\x1a\n") + + +def _t2i(env: RedactedEnv, target: Path, *extra: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "gflow_cli", "image", "t2i", "a paper boat on a pond", + "--out-file", str(target), *extra], + capture_output=True, + text=True, + check=False, + env=env | {"GFLOW_CLI_TRANSPORT": "direct_http"}, + ) + + +def _image_transports(env: RedactedEnv) -> list[str | None]: + with sqlite3.connect(env["GFLOW_CLI_DB_PATH"]) as db: + rows = db.execute("SELECT metadata_json FROM assets WHERE kind = 'image'").fetchall() + return [json.loads(row[0] or "{}").get("transport") for row in rows] + + +def _saved(target: Path) -> Path: + found = sorted(target.parent.glob(f"{target.stem}.*")) + assert len(found) == 1, f"expected one file for {target}, found {found}" + assert found[0].read_bytes().startswith(_JPEG_OR_PNG), f"{found[0]} is not an image" + return found[0] + + +def test_plain_t2i_is_generated_by_the_direct_transport( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + proc = _t2i(e2e_env, tmp_path / "direct.jpg") + assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" + _saved(tmp_path / "direct.jpg") + assert _image_transports(e2e_env) == ["direct_http"] + + +def test_an_unserved_aspect_routes_to_the_ui_transport( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + proc = _t2i(e2e_env, tmp_path / "wide.jpg", "--aspect", "16:9") + assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" + _saved(tmp_path / "wide.jpg") + assert _image_transports(e2e_env) == [None] From c37b73d08e3f82de698fbad1673e526c9c94930d Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:44:35 +0000 Subject: [PATCH 15/32] test(e2e): the queued MCP worker path runs a t2i on direct_http (T1.7) FlowWorker.process_task on a t2i task naming transport direct_http; the catalog records the image as made by that transport. --- tests/e2e/test_direct_image_worker_e2e.py | 68 +++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 tests/e2e/test_direct_image_worker_e2e.py diff --git a/tests/e2e/test_direct_image_worker_e2e.py b/tests/e2e/test_direct_image_worker_e2e.py new file mode 100644 index 000000000..ab6bb4b46 --- /dev/null +++ b/tests/e2e/test_direct_image_worker_e2e.py @@ -0,0 +1,68 @@ +"""Live proof that the queued MCP path runs the direct_http image transport (T1.7). + +The MCP server queues ``gflow_generate_image(wait=False)`` and ``FlowWorker`` runs it: a +different code path from the CLI's in-process call. This drives ``FlowWorker.process_task`` +on a ``t2i`` task whose payload names ``transport: "direct_http"`` and checks the catalog +records the image as made by that transport. + +Cost: one image (daily quota, zero credits). Opt-in: ``-m e2e_image`` with +``GFLOW_CLI_E2E_PROFILE`` set. +""" + +from __future__ import annotations + +import json +import uuid +from typing import TYPE_CHECKING + +import pytest + +from gflow_cli.worker.daemon import FlowWorker + +if TYPE_CHECKING: + from pathlib import Path + +pytestmark = [pytest.mark.e2e, pytest.mark.e2e_image] + + +@pytest.mark.asyncio +async def test_the_worker_runs_a_queued_t2i_on_the_direct_transport( + e2e_profile_dir: Path, tmp_path: Path +) -> None: + profile_name = e2e_profile_dir.name.removeprefix("profile_") + out_dir = tmp_path / "out" + out_dir.mkdir() + worker = FlowWorker(profile_name, str(tmp_path / "worker.db")) + try: + worker.db.conn.execute( # the queue's FK needs the profile row in this isolated DB + "INSERT INTO profiles(name, profile_dir, first_seen_at) VALUES (?, ?, ?)", + (profile_name, str(e2e_profile_dir), "2026-01-01T00:00:00Z"), + ) + task_id = f"e2e-direct-worker-{uuid.uuid4().hex[:8]}" + worker.repo.enqueue_task( + task_id, + profile_name, + "t2i", + { + "prompt": "a glass marble on a wooden table", + "aspect": "9:16", + # output_file, not out_dir: out_dir only feeds the client's debug artefacts; + # without output_file the worker saves into the user's real output folder. + "output_file": str(out_dir / "direct.jpg"), + "transport": "direct_http", + }, + ) + claimed = worker.repo.claim_next_pending(profile_name, f"worker:{profile_name}:e2e") + assert claimed is not None + await worker.process_task(claimed) + + done = worker.repo.get_task(task_id) + assert done is not None + assert done.status == "completed", f"status={done.status!r} error={done.error!r}" + rows = worker.db.conn.execute( + "SELECT metadata_json FROM assets WHERE kind = 'image'" + ).fetchall() + assert [json.loads(r[0] or "{}").get("transport") for r in rows] == ["direct_http"] + assert len(list(out_dir.iterdir())) == 1 + finally: + worker.close() From df44a5edb55bf68b0935d22ed9adc5c3529977c1 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:51:11 +0000 Subject: [PATCH 16/32] test: mirror GeneratedImage.transport on the worker test fakes The fakes copy GeneratedImage's fields; the recorder and the telemetry call site now read transport. --- tests/mcp/test_tools_wired.py | 1 + tests/worker/test_daemon.py | 1 + 2 files changed, 2 insertions(+) diff --git a/tests/mcp/test_tools_wired.py b/tests/mcp/test_tools_wired.py index b975c5367..00457951e 100644 --- a/tests/mcp/test_tools_wired.py +++ b/tests/mcp/test_tools_wired.py @@ -52,6 +52,7 @@ class _FakeImage: seed: int = 12345 fife_url: str = "http://fake" display_name: str | None = None # mirrors GeneratedImage.display_name + transport: str | None = None # mirrors GeneratedImage.transport def _completed_video_result(media_id: str = "media-vid-wired") -> VideoResult: diff --git a/tests/worker/test_daemon.py b/tests/worker/test_daemon.py index 699ee9900..f8e036fa4 100644 --- a/tests/worker/test_daemon.py +++ b/tests/worker/test_daemon.py @@ -33,6 +33,7 @@ class FakeGeneratedImage: seed: int = 12345 fife_url: str = "http://fake" display_name: str | None = None # mirrors GeneratedImage.display_name + transport: str | None = None # mirrors GeneratedImage.transport def _completed_video_result(media_id: str = "media-vid-123") -> VideoResult: From 6e71af6a3ed56f11f8d723694dc101f769db5c7c Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sun, 22 Nov 2026 23:57:06 +0000 Subject: [PATCH 17/32] feat(transport): serve every aspect and up to two images on the direct path (T2.3, T2.4) entry[4] carries the aspect (1:1=1, 9:16=2, 16:9=3, 3:4=4, 4:3=5, from route-aborted captures of Flow's own submit); a count is one entry per image in one POST, each with its own seed. Two entries returned two images live. The runner is split into read steps (session headers, shell tokens) and write steps (mint, request, one send). --- src/gflow_cli/api/transports/direct_http.py | 318 +++++++++--------- src/gflow_cli/api/transports/frame_builder.py | 66 ++-- tests/api/transports/test_direct_http.py | 39 ++- tests/api/transports/test_frame_builder.py | 52 ++- tests/e2e/test_direct_image_e2e.py | 38 ++- 5 files changed, 302 insertions(+), 211 deletions(-) diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 8b09aefbc..f3b47a9b9 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -8,7 +8,7 @@ from collections.abc import Callable from dataclasses import replace from http.cookiejar import CookieJar, DefaultCookiePolicy -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from urllib.parse import urlencode import httpx @@ -16,7 +16,7 @@ from gflow_cli.api import flow_wire from gflow_cli.api._engine import mint_evaluate_kwargs -from gflow_cli.api.image import Aspect, Model +from gflow_cli.api.image import Model from gflow_cli.api.recaptcha import TokenMinter from gflow_cli.api.transports._common import migrated_route from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images @@ -41,44 +41,155 @@ _WIRE_MODEL: dict[Model, str] = {Model.NARWHAL: "BELUGA"} +# Counts measured on the direct path (one POST with two entries returned two images). +_MAX_DIRECT_COUNT = 2 +_ORIGIN = "https://flow.google.com" +_RECONCILE_HINT = ( + "Flow may have accepted this image request before the error, so gflow did not resend " + "it. Check the project in Flow for the new image before running the command again." +) + + def direct_can_serve(request: GenerateImageRequest) -> bool: - """Return True only for plain T2I requests supported by direct HTTP. + """True only for a request whose every wire slot is measured. - Excludes reference images (refs, ref_paths), character entities, - non-portrait aspect ratios, multi-image counts, Agent instructions, - and character mentions (@). + T2I with a measured model, any aspect, and up to ``_MAX_DIRECT_COUNT`` images. No + reference images, character entities, Agent instructions or ``@`` mentions yet. """ - if request.aspect is not Aspect.PORTRAIT or request.model not in _WIRE_MODEL: - return False - if request.count != 1: - return False - if bool(request.refs) or bool(request.ref_paths) or bool(request.reference_entities): - return False - if bool(request.instructions): - return False - if "@" in request.prompt: - return False - return True + return ( + request.model in _WIRE_MODEL + and request.count <= _MAX_DIRECT_COUNT + and not (request.refs or request.ref_paths or request.reference_entities) + and not request.instructions + and "@" not in request.prompt + ) class _DirectFallbackError(Exception): - """Internal sentinel indicating the direct path should fall back to UI automation.""" + """Internal sentinel: nothing was sent, so the UI transport may run instead.""" def __init__(self, reason: str) -> None: super().__init__(reason) self.reason = reason -class DirectImageHttpRunner: - """Collaborator executing the direct HTTP sequence for image generation. +def _reconcile_error(detail: str, *, status: int | None = None) -> NetworkError: + """A failure after the POST was sent: never resent, the caller reconciles.""" + return NetworkError( + detail=f"{detail}; not resent", + status=status, + route="batchexecute:ogiZ0b", + next_action="reconcile", + remediation_hint=_RECONCILE_HINT, + ) + + +async def _session_headers(page: Page, profile_dir: Path) -> dict[str, str]: + """Read path: the live browser's cookies (the on-disk store is locked while Chrome + holds the profile) and the profile's own user agent.""" + try: + cookies = await page.context.cookies([_ORIGIN]) + except Exception as exc: + raise _DirectFallbackError(f"cookie_error:{type(exc).__name__}") from exc + cookie_header = "; ".join( + f"{name}={value}" for c in cookies if (name := c.get("name")) and (value := c.get("value")) + ) + if not cookie_header: + raise _DirectFallbackError("cookies_empty") + headers = {"accept-language": "en-US,en;q=0.9", "cookie": cookie_header} + if ua := flow_wire.user_agent(profile_dir): + headers["user-agent"] = ua + return headers + + +async def _shell( + client: httpx.AsyncClient, profile_dir: Path, headers: dict[str, str] +) -> flow_wire.Tokens: + """Read path: ``at`` / ``f.sid`` / ``bl`` from flow_wire's shell GET.""" + try: + return await flow_wire.shell_tokens(client, profile_dir, headers) + except flow_wire.WireReadUnavailable as exc: + raise _DirectFallbackError(exc.reason.value) from exc + except Exception as exc: + raise _DirectFallbackError(f"shell_tokens:{type(exc).__name__}") from exc + + +async def _mint(page: Page, project_id: str) -> str: + """The single browser step: an IMAGE_GENERATION token minted on the project page.""" + target = f"{_ORIGIN}/project/{project_id}" + try: + if not page.url.startswith(target): + await page.goto(target) + minter = TokenMinter(page, mint_evaluate_kwargs=mint_evaluate_kwargs()) + return await minter.mint("IMAGE_GENERATION") + except Exception as exc: + raise _DirectFallbackError(f"mint_failure:{type(exc).__name__}") from exc + + +def _post_request( + project_id: str, tokens: flow_wire.Tokens, headers: dict[str, str], body: str +) -> httpx.Request: + query = { + "rpcids": "ogiZ0b", + "source-path": f"/project/{project_id}", + "bl": tokens.bl, + "f.sid": tokens.fsid, + "hl": "en", + "_reqid": str(1000 + secrets.randbelow(9000)), + "rt": "c", + } + return httpx.Request( + "POST", + f"{_ORIGIN}/_/AiSandboxAngularFrontend/data/batchexecute?" + f"{urlencode({k: v for k, v in query.items() if v is not None})}", + content=body, + headers={ + **headers, + "content-type": "application/x-www-form-urlencoded;charset=UTF-8", + "x-same-domain": "1", + "origin": _ORIGIN, + "referer": f"{_ORIGIN}/project/{project_id}", + "sec-fetch-site": "same-origin", + "sec-fetch-mode": "cors", + "sec-fetch-dest": "empty", + }, + ) + + +async def _send_once(client: httpx.AsyncClient, request: httpx.Request) -> httpx.Response: + """Write path: exactly one send. A connect error reached nothing; anything after it may + have been billed and is never resent.""" + try: + response = await client.send(request) + except httpx.ConnectError as exc: + raise _DirectFallbackError("connect_error") from exc + except (httpx.TimeoutException, httpx.TransportError) as exc: + cause = (str(exc).strip().splitlines() or [""])[0][:160] + raise _reconcile_error(f"{type(exc).__name__} on an image submit ({cause})") from exc + if response.status_code == 403: + raise _DirectFallbackError("http_403") + if response.status_code != 200: + raise _reconcile_error( + f"HTTP {response.status_code} on an image submit", status=response.status_code + ) + return response - Coordinates live cookies, shell tokens, page minting, ogiZ0b frame building, - batchexecute POST, and response parsing. - """ + +class DirectImageHttpRunner: + """Runs one direct image generation: read the session, mint, build, send once, parse.""" def __init__(self, *, http_transport: httpx.AsyncBaseTransport | None = None) -> None: self._http_transport = http_transport + def _client(self) -> httpx.AsyncClient: + return httpx.AsyncClient( + follow_redirects=False, + trust_env=False, # nothing env-derived (proxies, netrc) reaches this client + timeout=httpx.Timeout(120.0, connect=10.0), # a generation takes 16-24 s + cookies=CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])), + transport=self._http_transport, # None = httpx's default; a mock under test + ) + async def run( self, *, @@ -87,157 +198,40 @@ async def run( project_id: str, request: GenerateImageRequest, ) -> list[GeneratedImage]: - t_start = time.perf_counter() - - # 1. Read live cookies from browser context - try: - cookie_list = await page.context.cookies(["https://flow.google.com"]) - cookie_parts = [ - f"{name}={value}" - for c in cookie_list - if (name := c.get("name")) and (value := c.get("value")) - ] - cookie_header = "; ".join(cookie_parts) - if not cookie_header: - raise _DirectFallbackError("cookies_empty") - except _DirectFallbackError: - raise - except Exception as exc: - raise _DirectFallbackError(f"cookie_error:{type(exc).__name__}") from exc - - # 2. Shell headers and user agent - ua = flow_wire.user_agent(profile_dir) - headers = { - "accept-language": "en-US,en;q=0.9", - "cookie": cookie_header, - } - if ua: - headers["user-agent"] = ua - - client_kwargs: dict[str, Any] = { - "follow_redirects": False, - "trust_env": False, - "timeout": httpx.Timeout(120.0, connect=10.0), - "cookies": CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])), - } - if self._http_transport is not None: - client_kwargs["transport"] = self._http_transport - - async with httpx.AsyncClient(**client_kwargs) as client: - # 3. Shell tokens - try: - tokens = await flow_wire.shell_tokens(client, profile_dir, headers) - except flow_wire.WireReadUnavailable as exc: - raise _DirectFallbackError(exc.reason.value) from exc - except Exception as exc: - raise _DirectFallbackError(f"shell_tokens:{type(exc).__name__}") from exc - - # 4. Page navigation check & reCAPTCHA token minting - target_url = f"https://flow.google.com/project/{project_id}" - if not page.url.startswith(target_url): - try: - await page.goto(target_url) - except Exception as exc: - raise _DirectFallbackError(f"navigation_failed:{type(exc).__name__}") from exc - - mint_start = time.perf_counter() - try: - token = await TokenMinter(page, mint_evaluate_kwargs=mint_evaluate_kwargs()).mint( - "IMAGE_GENERATION" - ) - except Exception as exc: - raise _DirectFallbackError("mint_failure") from exc - mint_ms = int((time.perf_counter() - mint_start) * 1000) - - # 5. Build ogiZ0b body - batch_id = str(uuid.uuid4()).upper() - session_counter = 1 + secrets.randbelow(2**31 - 1) + started = time.perf_counter() + headers = await _session_headers(page, profile_dir) + async with self._client() as client: + tokens = await _shell(client, profile_dir, headers) + mint_started = time.perf_counter() + token = await _mint(page, project_id) + mint_ms = int((time.perf_counter() - mint_started) * 1000) body = build_ogiz0b_body( prompt=request.prompt, model=_WIRE_MODEL[request.model], project_id=project_id, recaptcha_token=token, at_token=tokens.at, - batch_id=batch_id, - session_counter=session_counter, + batch_id=str(uuid.uuid4()).upper(), + entry_seeds=tuple(1 + secrets.randbelow(2**31 - 1) for _ in range(request.count)), + aspect=request.aspect, ) log.info( "direct.frame_built", model=request.model.value, prompt_length=len(request.prompt), + count=request.count, ) - - # 6. POST - query = { - "rpcids": "ogiZ0b", - "source-path": f"/project/{project_id}", - "bl": tokens.bl, - "f.sid": tokens.fsid, - "hl": "en", - "_reqid": str(1000 + secrets.randbelow(9000)), - "rt": "c", - } - post_url = ( - f"https://flow.google.com/_/AiSandboxAngularFrontend/data/batchexecute?" - f"{urlencode({k: v for k, v in query.items() if v is not None})}" - ) - post_headers = { - **headers, - "content-type": "application/x-www-form-urlencoded;charset=UTF-8", - "x-same-domain": "1", - "origin": "https://flow.google.com", - "referer": f"https://flow.google.com/project/{project_id}", - "sec-fetch-site": "same-origin", - "sec-fetch-mode": "cors", - "sec-fetch-dest": "empty", - } - - post_start = time.perf_counter() - try: - response = await client.post(post_url, content=body, headers=post_headers) - except httpx.ConnectError as exc: - raise _DirectFallbackError("connect_error") from exc - except (httpx.TimeoutException, httpx.TransportError) as exc: - cause = (str(exc).strip().splitlines() or [""])[0][:160] - raise NetworkError( - detail=f"{type(exc).__name__} on an image submit ({cause}); not resent", - route="batchexecute:ogiZ0b", - next_action="reconcile", - remediation_hint=( - "Flow may have accepted this image request before the error, so gflow " - "did not resend it. Check the project in Flow for the new image before " - "running the command again." - ), - ) from exc - - post_ms = int((time.perf_counter() - post_start) * 1000) - total_ms = int((time.perf_counter() - t_start) * 1000) - log.info( - "direct.image_post", - status=response.status_code, - mint_ms=mint_ms, - post_ms=post_ms, - total_ms=total_ms, - ) - - if response.status_code == 403: - raise _DirectFallbackError("http_403") - - if response.status_code != 200: - raise NetworkError( - detail=f"HTTP {response.status_code} on an image submit; not resent", - status=response.status_code, - route="batchexecute:ogiZ0b", - next_action="reconcile", - remediation_hint=( - "Flow may have accepted this image request before the error, so gflow " - "did not resend it. Check the project in Flow for the new image before " - "running the command again." - ), - ) - - images = ogiz0b_reply_images(response.text, request) - return [replace(img, transport="direct_http") for img in images] + post_started = time.perf_counter() + response = await _send_once(client, _post_request(project_id, tokens, headers, body)) + log.info( + "direct.image_post", + status=response.status_code, + mint_ms=mint_ms, + post_ms=int((time.perf_counter() - post_started) * 1000), + total_ms=int((time.perf_counter() - started) * 1000), + ) + images = ogiz0b_reply_images(response.text, request) + return [replace(img, transport="direct_http") for img in images] class DirectHttpTransport(UiAutomationTransport): diff --git a/src/gflow_cli/api/transports/frame_builder.py b/src/gflow_cli/api/transports/frame_builder.py index 71aec7f1f..b46408b43 100644 --- a/src/gflow_cli/api/transports/frame_builder.py +++ b/src/gflow_cli/api/transports/frame_builder.py @@ -1,14 +1,14 @@ """The ``ogiZ0b`` (image generation) batchexecute body, built from domain values. A pure function: no I/O, no clock, no randomness. The caller supplies the per-request -values (``batch_id``, ``session_counter``) so the output is deterministic under test. +values (``batch_id``, ``entry_seeds``) so the output is deterministic under test. -Wire shape (proven 2026-11-22, docs/superpowers/spikes/2026-11-22-ogiz0b-minimum-viable-frame.md): +Wire shape (proven 2026-11-22, docs/superpowers/spikes/2026-11-22-direct-image-gate0.md): ctx = [null, 22, null, null, null, project_id, null, null, null, null, [token, 1]] - entry = [null, null, null, session_counter, 2, model, null, copy(ctx), [[[prompt]]], + entry = [null, null, null, seed, aspect, model, null, copy(ctx), [[[prompt]]], null, null, null] - inner = [null, [entry], 1, ctx, [batch_id]] + inner = [null, [entry, ...], 1, ctx, [batch_id]] # one entry per image, one POST body = urlencode({"f.req": [[["ogiZ0b", json(inner), null, "generic"]]], "at": at}) """ @@ -17,7 +17,17 @@ import json from urllib.parse import urlencode -_ASPECT_PORTRAIT = 2 # Flow's 2026-11-22 submit capture sends 2 for portrait 9:16. +from gflow_cli.api.image import Aspect + +# entry[4], as Flow's own submit sends it (route-aborted captures, 2026-11-22). 9:16 and +# 16:9 are also proven by direct POSTs (768x1376, 1376x768); the other three by capture. +_ASPECT_WIRE: dict[Aspect, int] = { + Aspect.SQUARE: 1, + Aspect.PORTRAIT: 2, + Aspect.LANDSCAPE: 3, + Aspect.PORTRAIT_THREE_FOUR: 4, + Aspect.LANDSCAPE_FOUR_THREE: 5, +} def build_ogiz0b_body( @@ -28,36 +38,24 @@ def build_ogiz0b_body( recaptcha_token: str, at_token: str, batch_id: str, - session_counter: int, + entry_seeds: tuple[int, ...], + aspect: Aspect = Aspect.PORTRAIT, ) -> str: - """Return the form-encoded ``f.req`` + ``at`` body for one T2I ``ogiZ0b`` POST.""" - ctx: list[object] = [ - None, - 22, - None, - None, - None, - project_id, - None, - None, - None, - None, - [recaptcha_token, 1], - ] - entry: list[object] = [ - None, - None, - None, - session_counter, - _ASPECT_PORTRAIT, - model, - None, - ctx.copy(), - [[[prompt]]], - None, - None, - None, + """Return the form-encoded ``f.req`` + ``at`` body for one T2I ``ogiZ0b`` POST. + + One entry per image: ``len(entry_seeds)`` is the image count (two entries returned two + images in one POST, measured 2026-11-22). + """ + if not entry_seeds: + msg = "entry_seeds must name at least one image" + raise ValueError(msg) + ctx: list[object] = [None, 22, None, None, None, project_id, None, None, None, None] + ctx.append([recaptcha_token, 1]) + entries = [ + [None, None, None, seed, _ASPECT_WIRE[aspect], model, None, ctx.copy(), [[[prompt]]]] + + [None, None, None] + for seed in entry_seeds ] - inner = [None, [entry], 1, ctx, [batch_id]] + inner = [None, entries, 1, ctx, [batch_id]] f_req = json.dumps([[["ogiZ0b", json.dumps(inner, separators=(",", ":")), None, "generic"]]]) return urlencode({"f.req": f_req, "at": at_token}) diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index a03d0ff69..a93bb929a 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -32,15 +32,22 @@ def test_direct_can_serve_plain_t2i() -> None: assert direct_can_serve(req) is True +@pytest.mark.parametrize("aspect", list(Aspect)) +def test_direct_can_serve_every_measured_aspect(aspect: Aspect) -> None: + assert direct_can_serve(GenerateImageRequest(prompt="x", aspect=aspect)) is True + + +def test_direct_can_serve_two_images() -> None: + assert direct_can_serve(GenerateImageRequest(prompt="x", count=2)) is True + + @pytest.mark.parametrize( "kwargs", [ {"refs": (ImageRef(name="00000000-0000-0000-0000-000000000001"),)}, {"ref_paths": (Path("image.png"),)}, {"reference_entities": ("entity-1",)}, - {"aspect": Aspect.LANDSCAPE}, - {"aspect": Aspect.SQUARE}, - {"count": 2}, + {"count": 3}, # only count <= 2 is measured on the direct path {"instructions": (AgentInstruction(text="keep lighting dark"),)}, {"prompt": "A photo of @Alice in wonderland"}, ], @@ -681,3 +688,29 @@ def handler(request: httpx.Request) -> httpx.Response: @pytest.mark.parametrize("model", [m for m in Model if m is not Model.NARWHAL]) def test_a_model_with_no_measured_migrated_wire_name_is_not_served(model: Model) -> None: assert not direct_can_serve(GenerateImageRequest(prompt="x", model=model)) + + +@pytest.mark.asyncio +async def test_direct_http_sends_one_seed_per_image_and_the_aspect( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + builder = MagicMock(return_value="f.req=mock_body&at=at-x&") + monkeypatch.setattr("gflow_cli.api.transports.direct_http.build_ogiz0b_body", builder) + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + req = GenerateImageRequest(prompt="x", aspect=Aspect.LANDSCAPE, count=2) + await transport.generate_images(project_id="proj-123", request=req) + kwargs = builder.call_args.kwargs + assert len(kwargs["entry_seeds"]) == 2 + assert len(set(kwargs["entry_seeds"])) == 2 + assert kwargs["aspect"] is Aspect.LANDSCAPE diff --git a/tests/api/transports/test_frame_builder.py b/tests/api/transports/test_frame_builder.py index c98fcf7d2..b4b4164ae 100644 --- a/tests/api/transports/test_frame_builder.py +++ b/tests/api/transports/test_frame_builder.py @@ -5,6 +5,9 @@ import json from urllib.parse import parse_qs +import pytest + +from gflow_cli.api.image import Aspect from gflow_cli.api.transports.frame_builder import build_ogiz0b_body @@ -24,7 +27,7 @@ def test_builds_proven_ogiz0b_wire_shape() -> None: recaptcha_token="captcha-456", at_token="at-789", batch_id="batch-abc", - session_counter=12345, + entry_seeds=(12345,), ) form = parse_qs(body) @@ -62,7 +65,7 @@ def test_build_is_deterministic_for_the_same_inputs() -> None: "recaptcha_token": "captcha-456", "at_token": "at-789", "batch_id": "batch-abc", - "session_counter": 12345, + "entry_seeds": (12345,), } assert build_ogiz0b_body(**values) == build_ogiz0b_body(**values) @@ -77,7 +80,7 @@ def test_prompt_round_trips_through_form_and_compact_inner_json() -> None: recaptcha_token="captcha-456", at_token="at-789", batch_id="batch-abc", - session_counter=12345, + entry_seeds=(12345,), ) rpcid, inner, inner_json = _decode_body(body) @@ -85,3 +88,46 @@ def test_prompt_round_trips_through_form_and_compact_inner_json() -> None: assert rpcid == "ogiZ0b" assert inner[1][0][8] == [[[prompt]]] assert inner_json == json.dumps(inner, separators=(",", ":")) + + +@pytest.mark.parametrize( + ("aspect", "wire"), + [ + (Aspect.SQUARE, 1), + (Aspect.PORTRAIT, 2), + (Aspect.LANDSCAPE, 3), + (Aspect.PORTRAIT_THREE_FOUR, 4), + (Aspect.LANDSCAPE_FOUR_THREE, 5), + ], +) +def test_aspect_goes_to_entry_4_as_flows_own_enum(aspect: Aspect, wire: int) -> None: + """Values measured 2026-11-22 from route-aborted captures of Flow's own submit.""" + _, inner, _ = _decode_body(_build(aspect=aspect)) + assert inner[1][0][4] == wire + + +def test_count_is_one_entry_per_image_each_with_its_own_seed() -> None: + _, inner, _ = _decode_body(_build(entry_seeds=(11, 22))) + entries = inner[1] + assert [e[3] for e in entries] == [11, 22] + assert all(e[7] == inner[3] for e in entries) + assert entries[0] is not entries[1] + assert inner[4] == ["batch-abc"] # one batch id for the whole POST + + +def test_no_seed_is_refused() -> None: + with pytest.raises(ValueError, match="entry_seeds"): + _build(entry_seeds=()) + + +def _build(**overrides: object) -> str: + values: dict[str, object] = { + "prompt": "a fox", + "model": "IMAGEN", + "project_id": "project-123", + "recaptcha_token": "captcha-456", + "at_token": "at-789", + "batch_id": "batch-abc", + "entry_seeds": (12345,), + } + return build_ogiz0b_body(**(values | overrides)) # type: ignore[arg-type] diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index 5b8b653bb..369f626c7 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -1,9 +1,9 @@ -"""Live E2E for the direct_http image transport (T1.6). +"""Live E2E for the direct_http image transport (T1.6, T2.3, T2.4). A plain text-to-image run on ``GFLOW_CLI_TRANSPORT=direct_http`` is generated by one -direct ``ogiZ0b`` POST and recorded with ``metadata_json.transport = "direct_http"``; a -shape the direct path does not serve (16:9) is routed to the UI transport before any -POST and still generates. Both are image runs: daily quota, zero credits. +direct ``ogiZ0b`` POST and recorded with ``metadata_json.transport = "direct_http"``; two +16:9 images come from one direct POST; a model with no measured wire name is routed to the +UI transport before any POST and still generates. All image runs: daily quota, zero credits. Opt in with: GFLOW_CLI_E2E_PROFILE= uv run pytest -m e2e_image -v \\ @@ -32,8 +32,17 @@ def _t2i(env: RedactedEnv, target: Path, *extra: str) -> subprocess.CompletedProcess[str]: return subprocess.run( - [sys.executable, "-m", "gflow_cli", "image", "t2i", "a paper boat on a pond", - "--out-file", str(target), *extra], + [ + sys.executable, + "-m", + "gflow_cli", + "image", + "t2i", + "a paper boat on a pond", + "--out-file", + str(target), + *extra, + ], capture_output=True, text=True, check=False, @@ -63,10 +72,21 @@ def test_plain_t2i_is_generated_by_the_direct_transport( assert _image_transports(e2e_env) == ["direct_http"] -def test_an_unserved_aspect_routes_to_the_ui_transport( +def test_two_landscape_images_come_from_one_direct_post( e2e_env: RedactedEnv, tmp_path: Path ) -> None: - proc = _t2i(e2e_env, tmp_path / "wide.jpg", "--aspect", "16:9") + proc = _t2i(e2e_env, tmp_path / "wide.jpg", "--aspect", "16:9", "-n", "2") assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" - _saved(tmp_path / "wide.jpg") + files = sorted(p for p in tmp_path.iterdir() if p.name.startswith("wide")) + assert len(files) == 2, files + assert all(p.read_bytes().startswith(_JPEG_OR_PNG) for p in files) + assert _image_transports(e2e_env) == ["direct_http", "direct_http"] + + +def test_a_model_with_no_measured_wire_name_routes_to_the_ui_transport( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + proc = _t2i(e2e_env, tmp_path / "pro.jpg", "--model", "nano-pro") + assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" + _saved(tmp_path / "pro.jpg") assert _image_transports(e2e_env) == [None] From c41cc8a23f7758f641d445f09390b1263b89b962 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 00:06:27 +0000 Subject: [PATCH 18/32] feat(transport): serve a single in-project reference on the direct path (T2.1) Flow's own in-project I2I submit carries the media id at entry[2] and the id + display name as a chip ahead of the prompt text, which gains two leading spaces (captured 2026-11-22). Only that measured shape is served: one in-project reference with a display name, one image. --- src/gflow_cli/api/transports/direct_http.py | 13 ++++++++++- src/gflow_cli/api/transports/frame_builder.py | 16 ++++++++++--- tests/api/transports/test_direct_http.py | 23 +++++++++++++++++++ tests/api/transports/test_frame_builder.py | 15 ++++++++++++ 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index f3b47a9b9..76aa8f0fa 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -59,12 +59,22 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: return ( request.model in _WIRE_MODEL and request.count <= _MAX_DIRECT_COUNT - and not (request.refs or request.ref_paths or request.reference_entities) + and _references_measured(request) + and not (request.ref_paths or request.reference_entities) and not request.instructions and "@" not in request.prompt ) +def _references_measured(request: GenerateImageRequest) -> bool: + """No refs, or the one measured I2I shape: a single in-project image with a display + name (the chip needs it), one output image. A local file needs an upload first.""" + if not request.refs: + return True + (ref, *more) = request.refs + return not more and ref.in_project and bool(ref.display_name) and request.count == 1 + + class _DirectFallbackError(Exception): """Internal sentinel: nothing was sent, so the UI transport may run instead.""" @@ -214,6 +224,7 @@ async def run( batch_id=str(uuid.uuid4()).upper(), entry_seeds=tuple(1 + secrets.randbelow(2**31 - 1) for _ in range(request.count)), aspect=request.aspect, + references=tuple((ref.name, ref.display_name) for ref in request.refs), ) log.info( "direct.frame_built", diff --git a/src/gflow_cli/api/transports/frame_builder.py b/src/gflow_cli/api/transports/frame_builder.py index b46408b43..74c28b476 100644 --- a/src/gflow_cli/api/transports/frame_builder.py +++ b/src/gflow_cli/api/transports/frame_builder.py @@ -40,19 +40,29 @@ def build_ogiz0b_body( batch_id: str, entry_seeds: tuple[int, ...], aspect: Aspect = Aspect.PORTRAIT, + references: tuple[tuple[str, str], ...] = (), ) -> str: - """Return the form-encoded ``f.req`` + ``at`` body for one T2I ``ogiZ0b`` POST. + """Return the form-encoded ``f.req`` + ``at`` body for one ``ogiZ0b`` POST. One entry per image: ``len(entry_seeds)`` is the image count (two entries returned two - images in one POST, measured 2026-11-22). + images in one POST, measured 2026-11-22). ``references`` are in-project images as + ``(media_id, display_name)``: Flow's own I2I submit carries each at ``entry[2]`` and + as a chip ahead of the prompt text, which then starts with two spaces (captured + 2026-11-22 with one reference). """ if not entry_seeds: msg = "entry_seeds must name at least one image" raise ValueError(msg) ctx: list[object] = [None, 22, None, None, None, project_id, None, None, None, None] ctx.append([recaptcha_token, 1]) + media = [[media_id, None, None, None, 1] for media_id, _ in references] or None + document = ( + [[[None, [[media_id, name] for media_id, name in references]], [f" {prompt}"]]] + if references + else [[[prompt]]] + ) entries = [ - [None, None, None, seed, _ASPECT_WIRE[aspect], model, None, ctx.copy(), [[[prompt]]]] + [None, None, media, seed, _ASPECT_WIRE[aspect], model, None, ctx.copy(), document] + [None, None, None] for seed in entry_seeds ] diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index a93bb929a..15ee35ca3 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +from dataclasses import replace from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock @@ -714,3 +715,25 @@ def handler(request: httpx.Request) -> httpx.Response: assert len(kwargs["entry_seeds"]) == 2 assert len(set(kwargs["entry_seeds"])) == 2 assert kwargs["aspect"] is Aspect.LANDSCAPE + + +_IN_PROJECT = ImageRef( + name="00000000-0000-0000-0000-000000000002", display_name="Lighthouse", in_project=True +) + + +def test_direct_can_serve_one_in_project_reference() -> None: + assert direct_can_serve(GenerateImageRequest(prompt="x", refs=(_IN_PROJECT,))) is True + + +@pytest.mark.parametrize( + "kwargs", + [ + {"refs": (_IN_PROJECT, replace(_IN_PROJECT, name="00000000-0000-0000-0000-000000000003"))}, + {"refs": (replace(_IN_PROJECT, display_name=""),)}, + {"refs": (replace(_IN_PROJECT, in_project=False),)}, + {"refs": (_IN_PROJECT,), "count": 2}, + ], +) +def test_direct_can_serve_refuses_unmeasured_reference_shapes(kwargs: dict[str, object]) -> None: + assert direct_can_serve(GenerateImageRequest(prompt="x", **kwargs)) is False # type: ignore[arg-type] diff --git a/tests/api/transports/test_frame_builder.py b/tests/api/transports/test_frame_builder.py index b4b4164ae..f68735258 100644 --- a/tests/api/transports/test_frame_builder.py +++ b/tests/api/transports/test_frame_builder.py @@ -131,3 +131,18 @@ def _build(**overrides: object) -> str: "entry_seeds": (12345,), } return build_ogiz0b_body(**(values | overrides)) # type: ignore[arg-type] + + +def test_an_in_project_reference_rides_slot_2_and_a_prompt_chip() -> None: + """Flow's own in-project I2I submit, captured 2026-11-22: the media id at entry[2], and + the same id + display name as a chip ahead of the text (which gains two spaces).""" + _, inner, _ = _decode_body(_build(references=(("media-1", "Lighthouse"),))) + entry = inner[1][0] + assert entry[2] == [["media-1", None, None, None, 1]] + assert entry[8] == [[[None, [["media-1", "Lighthouse"]]], [" a fox"]]] + + +def test_no_reference_keeps_the_plain_prompt_document() -> None: + _, inner, _ = _decode_body(_build()) + assert inner[1][0][2] is None + assert inner[1][0][8] == [[["a fox"]]] From b2576e8a9648621691bf5be88de5e1e300562fc9 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 00:14:52 +0000 Subject: [PATCH 19/32] fix(transport): wait for reCAPTCHA after navigating before a direct mint A direct run that starts off the project page navigated there and minted at once; grecaptcha.enterprise was not loaded yet, the mint raised RecaptchaError and the run fell back to the UI (measured live on an i2i with --project). A mint spends nothing, so it is retried for up to 10 s. Adds the live in-project i2i e2e. --- src/gflow_cli/api/transports/direct_http.py | 21 +++++++++++-- tests/api/transports/test_direct_http.py | 32 +++++++++++++++++++ tests/e2e/test_direct_image_e2e.py | 35 +++++++++++++++++++++ 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 76aa8f0fa..9952c76c8 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import secrets import time import uuid @@ -23,7 +24,7 @@ from gflow_cli.api.transports.frame_builder import build_ogiz0b_body from gflow_cli.api.transports.ui_automation import UiAutomationTransport from gflow_cli.config import get_settings -from gflow_cli.errors import NetworkError +from gflow_cli.errors import NetworkError, RecaptchaError if TYPE_CHECKING: from pathlib import Path @@ -44,6 +45,8 @@ # Counts measured on the direct path (one POST with two entries returned two images). _MAX_DIRECT_COUNT = 2 _ORIGIN = "https://flow.google.com" +_MINT_BUDGET_S = 10.0 # how long a freshly navigated page gets to load reCAPTCHA +_MINT_RETRY_S = 0.5 _RECONCILE_HINT = ( "Flow may have accepted this image request before the error, so gflow did not resend " "it. Check the project in Flow for the new image before running the command again." @@ -125,13 +128,25 @@ async def _shell( async def _mint(page: Page, project_id: str) -> str: - """The single browser step: an IMAGE_GENERATION token minted on the project page.""" + """The single browser step: an IMAGE_GENERATION token minted on the project page. + + Right after a navigation the enterprise script is not loaded yet and the mint raises + ``RecaptchaError`` (measured 2026-11-23 on an i2i run with ``--project``). A mint spends + nothing, so it is retried until the script answers or the budget runs out. + """ target = f"{_ORIGIN}/project/{project_id}" try: if not page.url.startswith(target): await page.goto(target) minter = TokenMinter(page, mint_evaluate_kwargs=mint_evaluate_kwargs()) - return await minter.mint("IMAGE_GENERATION") + deadline = time.monotonic() + _MINT_BUDGET_S + while True: + try: + return await minter.mint("IMAGE_GENERATION") + except RecaptchaError: + if time.monotonic() >= deadline: + raise + await asyncio.sleep(_MINT_RETRY_S) except Exception as exc: raise _DirectFallbackError(f"mint_failure:{type(exc).__name__}") from exc diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 15ee35ca3..4de056565 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -737,3 +737,35 @@ def test_direct_can_serve_one_in_project_reference() -> None: ) def test_direct_can_serve_refuses_unmeasured_reference_shapes(kwargs: dict[str, object]) -> None: assert direct_can_serve(GenerateImageRequest(prompt="x", **kwargs)) is False # type: ignore[arg-type] + + +@pytest.mark.asyncio +async def test_a_mint_on_a_page_still_loading_recaptcha_is_retried_not_dropped( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + """Live 2026-11-23: an i2i with --project navigates to the project and mints at once; + grecaptcha.enterprise is not loaded yet, and the run fell back to the UI.""" + from gflow_cli.errors import RecaptchaError + + monkeypatch.setattr("gflow_cli.api.transports.direct_http._MINT_RETRY_S", 0.0) + mint = AsyncMock(side_effect=[RecaptchaError("grecaptcha.enterprise not loaded"), "tok"]) + monkeypatch.setattr("gflow_cli.api.recaptcha.TokenMinter.mint", mint) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.build_ogiz0b_body", + MagicMock(return_value="f.req=mock_body&at=at-x&"), + ) + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + transport._page.url = "about:blank" # type: ignore[union-attr] + images = await transport.generate_images( + project_id="proj-123", request=GenerateImageRequest(prompt="x") + ) + assert images[0].transport == "direct_http" + assert mint.await_count == 2 diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index 369f626c7..9679a57e6 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -90,3 +90,38 @@ def test_a_model_with_no_measured_wire_name_routes_to_the_ui_transport( assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" _saved(tmp_path / "pro.jpg") assert _image_transports(e2e_env) == [None] + + +def test_an_in_project_reference_is_generated_by_the_direct_transport( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + """T2.1: an i2i whose --ref is an image this project already holds goes direct.""" + first = _t2i(e2e_env, tmp_path / "source.jpg") + assert first.returncode == 0, f"gflow image t2i failed (exit {first.returncode})" + with sqlite3.connect(e2e_env["GFLOW_CLI_DB_PATH"]) as db: + media_id, project_id = db.execute( + "SELECT flow_media_id, flow_project_id FROM assets WHERE kind = 'image'" + ).fetchone() + proc = subprocess.run( + [ + sys.executable, + "-m", + "gflow_cli", + "image", + "i2i", + "the same scene at night", + "--ref", + media_id, + "--project", + project_id, + "--out-file", + str(tmp_path / "night.jpg"), + ], + capture_output=True, + text=True, + check=False, + env=e2e_env | {"GFLOW_CLI_TRANSPORT": "direct_http"}, + ) + assert proc.returncode == 0, f"gflow image i2i failed (exit {proc.returncode})" + _saved(tmp_path / "night.jpg") + assert _image_transports(e2e_env) == ["direct_http", "direct_http"] From 1014171acee9a8091266af92530c62394a84917b Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 00:19:51 +0000 Subject: [PATCH 20/32] feat(transport): serve one named character on the direct path (T2.2) Flow's own @Character submit carries the entity id at entry[10] and a character chip [null, [null, null, [id, name]]] ahead of the text, which gains one leading space (captured 2026-11-23). Only a request that already holds the id and its name is served; a bare @Name mention reaches the transport with no id and stays on the UI transport. --- src/gflow_cli/api/transports/direct_http.py | 22 ++++++++- src/gflow_cli/api/transports/frame_builder.py | 31 +++++++++--- tests/api/transports/test_direct_http.py | 47 +++++++++++++++++++ tests/api/transports/test_frame_builder.py | 15 ++++++ 4 files changed, 107 insertions(+), 8 deletions(-) diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 9952c76c8..e5e6a6513 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -63,7 +63,8 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: request.model in _WIRE_MODEL and request.count <= _MAX_DIRECT_COUNT and _references_measured(request) - and not (request.ref_paths or request.reference_entities) + and _characters_measured(request) + and not request.ref_paths and not request.instructions and "@" not in request.prompt ) @@ -78,6 +79,22 @@ def _references_measured(request: GenerateImageRequest) -> bool: return not more and ref.in_project and bool(ref.display_name) and request.count == 1 +def _characters_measured(request: GenerateImageRequest) -> bool: + """No character, or the one measured shape: a single entity id with its name (the chip + needs both), no image reference, one output image. A bare ``@Name`` mention carries no + id here (the UI picker resolves it in the browser), so it stays on the UI transport.""" + if not request.reference_entities: + return True + names = request.reference_entity_names + return ( + len(request.reference_entities) == 1 + and len(names) == 1 + and bool(names[0]) + and not request.refs + and request.count == 1 + ) + + class _DirectFallbackError(Exception): """Internal sentinel: nothing was sent, so the UI transport may run instead.""" @@ -240,6 +257,9 @@ async def run( entry_seeds=tuple(1 + secrets.randbelow(2**31 - 1) for _ in range(request.count)), aspect=request.aspect, references=tuple((ref.name, ref.display_name) for ref in request.refs), + characters=tuple( + zip(request.reference_entities, request.reference_entity_names, strict=True) + ), ) log.info( "direct.frame_built", diff --git a/src/gflow_cli/api/transports/frame_builder.py b/src/gflow_cli/api/transports/frame_builder.py index 74c28b476..27c19e396 100644 --- a/src/gflow_cli/api/transports/frame_builder.py +++ b/src/gflow_cli/api/transports/frame_builder.py @@ -41,6 +41,7 @@ def build_ogiz0b_body( entry_seeds: tuple[int, ...], aspect: Aspect = Aspect.PORTRAIT, references: tuple[tuple[str, str], ...] = (), + characters: tuple[tuple[str, str], ...] = (), ) -> str: """Return the form-encoded ``f.req`` + ``at`` body for one ``ogiZ0b`` POST. @@ -48,24 +49,40 @@ def build_ogiz0b_body( images in one POST, measured 2026-11-22). ``references`` are in-project images as ``(media_id, display_name)``: Flow's own I2I submit carries each at ``entry[2]`` and as a chip ahead of the prompt text, which then starts with two spaces (captured - 2026-11-22 with one reference). + 2026-11-22 with one reference). ``characters`` are ``(entity_id, name)``: each at + ``entry[10]`` and as a character chip, the text then starting with one space (captured + 2026-11-23 with one character). The two are never combined: that shape is unmeasured. """ if not entry_seeds: msg = "entry_seeds must name at least one image" raise ValueError(msg) ctx: list[object] = [None, 22, None, None, None, project_id, None, None, None, None] ctx.append([recaptcha_token, 1]) + if references and characters: + msg = "references and characters together are not a measured ogiZ0b shape" + raise ValueError(msg) media = [[media_id, None, None, None, 1] for media_id, _ in references] or None - document = ( - [[[None, [[media_id, name] for media_id, name in references]], [f" {prompt}"]]] - if references - else [[[prompt]]] - ) + entities = [[entity_id] for entity_id, _ in characters] or None + document = _prompt_document(prompt, references, characters) entries = [ [None, None, media, seed, _ASPECT_WIRE[aspect], model, None, ctx.copy(), document] - + [None, None, None] + + [None, entities, None] for seed in entry_seeds ] inner = [None, entries, 1, ctx, [batch_id]] f_req = json.dumps([[["ogiZ0b", json.dumps(inner, separators=(",", ":")), None, "generic"]]]) return urlencode({"f.req": f_req, "at": at_token}) + + +def _prompt_document( + prompt: str, + references: tuple[tuple[str, str], ...], + characters: tuple[tuple[str, str], ...], +) -> list[object]: + """``entry[8]``: the prompt as Flow's composer serialises it, chips first.""" + if references: + return [[[None, [[media_id, name] for media_id, name in references]], [f" {prompt}"]]] + if characters: + chips = [[None, None, [entity_id, name]] for entity_id, name in characters] + return [[[None, *chips], [f" {prompt}"]]] + return [[[prompt]]] diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 4de056565..bc35b18ec 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -769,3 +769,50 @@ def handler(request: httpx.Request) -> httpx.Response: ) assert images[0].transport == "direct_http" assert mint.await_count == 2 + + +_SKIPPER = {"reference_entities": ("entity-1",), "reference_entity_names": ("Skipper",)} + + +def test_direct_can_serve_one_named_character() -> None: + assert direct_can_serve(GenerateImageRequest(prompt="x", **_SKIPPER)) is True # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "kwargs", + [ + {"reference_entities": ("entity-1",)}, # a bare @Name mention: no name pair here + {"reference_entities": ("entity-1",), "reference_entity_names": ("",)}, + { + "reference_entities": ("entity-1", "entity-2"), + "reference_entity_names": ("Skipper", "Mate"), + }, + {**_SKIPPER, "refs": (_IN_PROJECT,)}, + {**_SKIPPER, "count": 2}, + ], +) +def test_direct_can_serve_refuses_unmeasured_character_shapes(kwargs: dict[str, object]) -> None: + assert direct_can_serve(GenerateImageRequest(prompt="x", **kwargs)) is False # type: ignore[arg-type] + + +@pytest.mark.asyncio +async def test_direct_http_sends_the_character_pair( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + builder = MagicMock(return_value="f.req=mock_body&at=at-x&") + monkeypatch.setattr("gflow_cli.api.transports.direct_http.build_ogiz0b_body", builder) + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + req = GenerateImageRequest(prompt="x", **_SKIPPER) # type: ignore[arg-type] + await transport.generate_images(project_id="proj-123", request=req) + assert builder.call_args.kwargs["characters"] == (("entity-1", "Skipper"),) diff --git a/tests/api/transports/test_frame_builder.py b/tests/api/transports/test_frame_builder.py index f68735258..fba3b671b 100644 --- a/tests/api/transports/test_frame_builder.py +++ b/tests/api/transports/test_frame_builder.py @@ -146,3 +146,18 @@ def test_no_reference_keeps_the_plain_prompt_document() -> None: _, inner, _ = _decode_body(_build()) assert inner[1][0][2] is None assert inner[1][0][8] == [[["a fox"]]] + + +def test_a_character_rides_slot_10_and_a_character_chip() -> None: + """Flow's own @Character submit, captured 2026-11-23: the entity id at entry[10], and a + character chip [null, [null, null, [id, name]]] ahead of the text (one leading space).""" + _, inner, _ = _decode_body(_build(characters=(("entity-1", "Skipper"),))) + entry = inner[1][0] + assert entry[10] == [["entity-1"]] + assert entry[2] is None + assert entry[8] == [[[None, [None, None, ["entity-1", "Skipper"]]], [" a fox"]]] + + +def test_no_character_leaves_slot_10_empty() -> None: + _, inner, _ = _decode_body(_build()) + assert inner[1][0][10] is None From be46d259d19dd90559d665fca760da3fc83ba1a3 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 00:21:41 +0000 Subject: [PATCH 21/32] test(e2e): a named character is generated by the direct transport (T2.2) Creates a character from a direct image (one generation, zero credits; GFLOW_CLI_E2E_RUN_CHARACTER=1), then a t2i with --reference-entity and its name goes direct. --- tests/e2e/test_direct_image_e2e.py | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index 9679a57e6..c4cdaa1cd 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -13,6 +13,7 @@ from __future__ import annotations import json +import os import sqlite3 import subprocess import sys @@ -125,3 +126,52 @@ def test_an_in_project_reference_is_generated_by_the_direct_transport( assert proc.returncode == 0, f"gflow image i2i failed (exit {proc.returncode})" _saved(tmp_path / "night.jpg") assert _image_transports(e2e_env) == ["direct_http", "direct_http"] + + +@pytest.mark.skipif( + os.environ.get("GFLOW_CLI_E2E_RUN_CHARACTER") != "1", + reason="creates a Flow character (one image generation, zero credits); opt in with " + "GFLOW_CLI_E2E_RUN_CHARACTER=1", +) +def test_a_named_character_is_generated_by_the_direct_transport( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + """T2.2: --reference-entity ID --reference-entity-name NAME goes direct.""" + first = _t2i(e2e_env, tmp_path / "face.jpg") + assert first.returncode == 0, f"gflow image t2i failed (exit {first.returncode})" + with sqlite3.connect(e2e_env["GFLOW_CLI_DB_PATH"]) as db: + (project_id,) = db.execute("SELECT flow_project_id FROM assets").fetchone() + made = subprocess.run( + [ + sys.executable, + "-m", + "gflow_cli", + "character", + "create", + "--project", + project_id, + "--name", + "Skipper", + "--image", + str(_saved(tmp_path / "face.jpg")), + ], + capture_output=True, + text=True, + check=False, + env=e2e_env, + ) + assert made.returncode == 0, f"gflow character create failed (exit {made.returncode})" + entity_id = made.stdout.split("Character created:", 1)[1].split()[0] + proc = _t2i( + e2e_env, + tmp_path / "pier.jpg", + "--project", + project_id, + "--reference-entity", + entity_id, + "--reference-entity-name", + "Skipper", + ) + assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" + _saved(tmp_path / "pier.jpg") + assert _image_transports(e2e_env)[-1] == "direct_http" From d51389ee3088c260e8d0bfb2e4085ff16d4b9dd2 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 00:25:56 +0000 Subject: [PATCH 22/32] =?UTF-8?q?docs:=20the=20direct=5Fhttp=20image=20tra?= =?UTF-8?q?nsport=20=E2=80=94=20user=20doc,=20Gate=200=20findings,=20plan?= =?UTF-8?q?=20record?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DIRECT_TRANSPORT.md lists the requests served directly (each with how it was measured), the fallback and no-resend rules, and what is recorded. Corrects the transports telemetry values (direct, ui, other). --- CHANGELOG.md | 3 +- docs/DIRECT_TRANSPORT.md | 71 +++ docs/INDEX.md | 1 + docs/TELEMETRY.md | 2 +- .../PLAN.md | 421 ++++++++++++++++++ .../spikes/2026-11-22-direct-image-gate0.md | 140 ++++++ scripts/dev/spike_direct_image_gate0.py | 362 +++++++++++++++ website/docs/TELEMETRY.md | 2 +- 8 files changed, 999 insertions(+), 3 deletions(-) create mode 100644 docs/DIRECT_TRANSPORT.md create mode 100644 docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md create mode 100644 docs/superpowers/spikes/2026-11-22-direct-image-gate0.md create mode 100644 scripts/dev/spike_direct_image_gate0.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c5e1611c0..0f9d0e9b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **The weekly usage report counts the image transport used.** A new field, `transports` (`direct`, `ui`, `other`, `unknown`), counts image generations by transport strategy (`direct` for direct HTTP, `ui` for UI automation, or `unknown` when none was noted), and generated asset metadata records `"transport": "direct_http"` when direct transport produced the image. The privacy notice moves to version 4 and names image transport. In the EU and EEA, consent given to an earlier notice version no longer counts: uploads stop until `gflow telemetry on` is run again. +- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one or two images, one in-project `--ref`, or one `--reference-entity` with its name; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and HTTP 403 falls back to the UI transport. +- **The weekly usage report counts the image transport used.** A new field, `transports` (`direct`, `ui`, `other`), counts image generations by transport strategy (`direct` for direct HTTP, `ui` for UI automation), and generated asset metadata records `"transport": "direct_http"` when direct transport produced the image. The privacy notice moves to version 4 and names image transport. In the EU and EEA, consent given to an earlier notice version no longer counts: uploads stop until `gflow telemetry on` is run again. ### Fixed diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md new file mode 100644 index 000000000..65d131db8 --- /dev/null +++ b/docs/DIRECT_TRANSPORT.md @@ -0,0 +1,71 @@ +# Direct HTTP image transport (`direct_http`, experimental) + +`direct_http` generates images on `flow.google.com` with one direct HTTP request to Flow's +`ogiZ0b` RPC instead of driving the composer page. The browser is still started and still +needed: it mints the reCAPTCHA token and holds the signed-in session. It no longer types +the prompt, opens the settings pane or clicks Generate. + +It is experimental. It is off unless you select it, and any request it cannot build +exactly goes to the default `ui_automation` transport before anything is sent. + +## Turning it on + +```bash +GFLOW_CLI_TRANSPORT=direct_http gflow image t2i "a paper boat on a pond" +``` + +The setting applies to `gflow image t2i` / `i2i` / `generate` and to the MCP image tool, +in-process and as a queued job. Batch runs (`gflow run`, `gflow image batch`) still use the +UI transport. + +## What it serves + +A request goes direct only when every slot of the frame it needs has been measured against +Flow's own submit. Everything else is routed to `ui_automation` before any request is sent. + +| Request | Direct | Measured by | +|---|---|---| +| Text-to-image, model `nano2` / `nano21` (sent as `BELUGA`) | yes | 10 consecutive live generations | +| Aspect 9:16, 16:9 | yes | live generations (768x1376, 1376x768) | +| Aspect 1:1, 4:3, 3:4 | yes | captures of Flow's own submit | +| Count 1 or 2 | yes | a live two-image generation in one request | +| One `--ref` to an image already in the project (with its display name) | yes | a live generation | +| One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | +| Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | +| Count 3 or 4 | no | not sent directly | +| Several refs, several characters, a ref plus a character | no | not captured | +| A local-file ref (`--ref ./photo.png`, needs an upload) | no | upload not ported | +| A bare `@Name` mention | no | the request carries no character id to send | +| Agent-mode instructions | no | not captured | +| A configured proxy (gflow's, the environment's or the OS's) | no | the browser and the request could leave by different routes | + +## Failure behaviour + +| What happens | Before the request is sent? | Result | +|---|---|---| +| The browser's cookies, the session tokens or the reCAPTCHA mint are unavailable | yes | the same request runs on `ui_automation` | +| The connection cannot be opened | yes | the same request runs on `ui_automation` | +| Flow answers HTTP 403 | no, but Flow refused it | the same request runs on `ui_automation` | +| A timeout, a dropped connection or any other HTTP status | no | the run stops with a network error (`next_action: reconcile`); gflow does **not** resend, because Flow may have made the image | +| Flow refuses the prompt | no | the same refusal error as the UI path | + +A sent request is never retried. A reCAPTCHA mint is retried for up to 10 seconds while the +page loads its reCAPTCHA script, because a mint spends nothing. + +## What it records + +- Each image's catalog row carries `"transport": "direct_http"` in its `metadata_json`. +- The weekly usage report counts image generations by transport (`direct`, `ui`): see + [TELEMETRY.md](TELEMETRY.md). +- Log events: `direct.frame_built`, `direct.image_post` (status, `mint_ms`, `post_ms`, + `total_ms`) and `direct.fallback_to_ui` (reason). Set `GFLOW_CLI_LOG_LEVEL=INFO` to see + them. Tokens, cookies, prompts and signed URLs are never logged. + +## Speed + +Measured on one profile, ten generations each, same prompt and model: the direct path took +a median of 18.6 s from mint to reply, the warm UI transport 20.7 s. Flow's own generation +time dominates both. The case for the transport is that it does not depend on the +composer's DOM, so selector changes and UI locale do not affect it. + +Evidence: [`docs/superpowers/spikes/2026-11-22-direct-image-gate0.md`](superpowers/spikes/2026-11-22-direct-image-gate0.md). diff --git a/docs/INDEX.md b/docs/INDEX.md index 670c980fe..5aaeb3d40 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -42,6 +42,7 @@ Welcome to the `gflow-cli` documentation. This index is the routing layer: it te | **[docs/DATA_LAYER.md](DATA_LAYER.md)** | Local SQLite catalog: goals, schema, recording flow, redaction, `gflow data` CLI, migrations, extension guide | Anything touching `gflow_cli.data`, debugging missing rows, building I2V/repair tooling, auditing what is stored | | **[docs/TELEMETRY.md](TELEMETRY.md)** | Usage data and privacy notice: local counters, the weekly report and exactly what it contains, EU/EEA consent, kill switches, `gflow telemetry on\|off\|status\|show` | Auditing what is counted and sent, turning uploads off or on, or giving EU/EEA consent | | **[docs/CHARACTER.md](CHARACTER.md)** | Characters feature spec & system design: domain model, endpoint/cost matrix, sequence diagrams, JSON payloads (I/O), CLI surface, reuse via `referenceEntities` (#145) | Working on `gflow character`, reusing a character in generations, or understanding Flow's character wire protocol | +| **[docs/DIRECT_TRANSPORT.md](DIRECT_TRANSPORT.md)** | The experimental `direct_http` image transport: one direct `ogiZ0b` request instead of the composer page, which requests it serves, its fallback and no-resend rules, what it records, measured speed | Turning it on with `GFLOW_CLI_TRANSPORT=direct_http`, or finding out why a request went to the UI transport | | **[docs/REFERENCE_STRATEGIES.md](REFERENCE_STRATEGIES.md)** | How to reference an asset: `@Name` mention vs `--reference-entity` vs `--ref` — the two-axis model (identity vs image), same-wire+dedupe rule, per-path support matrix, image-less-entity prerequisite, agent rule | Deciding how to tag a saved character/asset in a prompt, or wiring `@`-mentions into a generation | | **[docs/MEDIA_LIBRARY.md](MEDIA_LIBRARY.md)** | Flow's media library as a component: asset-kind taxonomy (`media[]`/`workflows[]`/preset voices), UUID-vs-displayName identity rules (AI caption ≤~35 chars, mutable, async, non-unique), the `projectInitialData` listing endpoint (complete, direct-GET-able), picker UI facts (virtualized grid, per-picker project, no a11y tree, single-click attach) + full pitfall table | Touching any picker/listing/reference code, or debugging why an asset "isn't found" | | **[docs/MOVIE.md](MOVIE.md)** | `gflow movie` — multi-scene character-consistent films: manifest format, run lifecycle (browser stays open through generate→poll→download), entity-attach mechanism (Personagens right-click), resume/handoff, credits | Working on `gflow movie`, debugging scene generation, or understanding the character-entity attach + consistency model | diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 1b2af0599..108ce0c0b 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -35,7 +35,7 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | -| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. Runs that noted no transport count as `unknown`. | +| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. A run that generated no image adds nothing to this map. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent diff --git a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md new file mode 100644 index 000000000..2d799db03 --- /dev/null +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -0,0 +1,421 @@ +# Plan — Direct HTTP Image Transport + +**Status:** Gate 0, Phase 1, Phase 2 and Phase 3 implemented; Phase 4 deferred +**Branch:** `feature/direct-http-image-transport` (off `develop`) +**Spike evidence:** `chore/spike-direct-image-with-browser-token` — 5 commits proving +each component end-to-end. Findings doc: +[`docs/superpowers/spikes/2026-11-22-direct-image-with-browser-token.md`](../spikes/2026-11-22-direct-image-with-browser-token.md) +Gate 0 findings: [`docs/superpowers/spikes/2026-11-22-direct-image-gate0.md`](../../spikes/2026-11-22-direct-image-gate0.md). + +## Goal + +Replace the browser-driven image generation path with direct HTTP calls for +text-to-image (T2I), in-project image-to-image (I2I), and character-mention +generations. The browser stays only for reCAPTCHA token minting. Everything +else — cookies, page tokens, frame building, the generation POST, the download +— is direct HTTP. + +**Why:** eliminates selector drift, locale sensitivity, and contenteditable +fragility for image generation. The UI transport clicks through a prompt editor, +waits for Angular renders, and parses a contenteditable document — the direct +path skips all of that. Latency improvement to be measured in Gate 0. + +--- + +## Architecture + +``` +┌───────────────────────────────────────────────┐ +│ CLI / MCP │ +│ generate_image(prompt, model, project, ...) │ +└──────────────┬────────────────────────────────┘ + │ FlowTransportStrategy.generate_images() + ▼ +┌──────────────────────────────────────┐ +│ DirectHttpTransport │ +│ │ +│ 0. can_serve(request)? │ ← route unsupported shapes to UI +│ 1. flow_wire session (reuse) │ ← cookies + at/fsid/bl already in flow_wire.py +│ 2. mint_recaptcha_token() │ ← page.evaluate() — ONLY browser step +│ 3. build_ogiz0b_frame(prompt, ...) │ ← pure function, no captured state +│ 4. httpx.post(batchexecute) │ ← reuse flow_wire's httpx + headers +│ 5. image_records(response) │ ← existing parser in batchexecute.py +│ 6. download signed URLs │ ← httpx, no cookies needed +└──────────────────────────────────────┘ +``` + +### Key reuse: `flow_wire.py` already exists + +`api/flow_wire.py` (#1229, #1363) already does direct batchexecute against +`flow.google.com` for credits reads and media mutations. It has: +- Cookie loading via `auth.cookies.read_cookies_for()` +- Page token scraping (`at`/`SNlM0e`, `fsid`/`FdrFJe`, `bl`/`cfb2h`) +- httpx POST to `/_/AiSandboxAngularFrontend/data/batchexecute` +- `parse_frames()` and `rpc_errors()` from `batchexecute.py` +- Fallback reason enum, structlog events, proxy detection, PSIDTS freshness + +**The direct image transport extends this infrastructure to the `ogiZ0b` RPC.** +No new cookie reader, no new token fetcher, no new httpx client. The only new +code is the frame builder (pure function) and the transport class that +orchestrates the existing pieces plus reCAPTCHA minting from the browser page. + +Inherited constraints from `flow_wire.py`: +- Skipped while any proxy is configured (`getproxies()`) +- macOS default-off unless `GFLOW_CLI_WIRE_READS=1` +- PSIDTS freshness: works ~1.5–2.5 h after a browser visit +- One account's failure never affects another + +### `can_serve()` gate — route before sending + +Before building a frame, check whether the request is in the proven surface: + +| Feature | can_serve? | Phase | +|---|---|---| +| Plain T2I, default aspect, count=1 | Yes (proven) | 1 | +| In-project I2I refs | Yes (format known) | 2 | +| Character mentions | Yes (format measured) | 2 | +| Non-default aspect ratio | **No until slot captured** | 2 (after T2.0) | +| Count > 1 | **No until semantics captured** | 2 (after T2.0b) | +| Local-file I2I (needs maseQ upload) | **No** | 4 (deferred) | + +A request outside the proven surface is routed to `ui_automation` **before any +POST**. This is not a fallback — it is the primary routing decision. The direct +path never sends a frame it cannot fully build. + +### Fallback policy + +Fallback to UI only on: +- **Pre-send:** `can_serve()` returns false (the common case while features are phased in) +- **Definitive rejection:** HTTP 403 (reCAPTCHA challenge) from the POST + +**No fallback on:** timeout, connection reset, HTTP 5xx. These are errors — log +them, raise, let the caller's retry/error path handle it. A timeout in +particular may mean the frame was billed. + +**Never retry a sent ogiZ0b** — it may have been billed. On any post-send failure, +return the error. + +--- + +## Proven in spike + +| Component | Evidence | Finding | +|---|---|---| +| On-disk cookie reading | SQLite parse → httpx POST succeeded | `d24f1952` | +| Programmatic frame (template swap) | Prompt + token swap → generation | `634a991c` | +| From-scratch frame builder | 12-slot minimum viable, `inner[4]` = `[uuid]` not `uuid` | `ee7fa2d7` | +| Slot optionality | Slots 12-14 optional | `16ab3d4b` | +| Predict verdict | GO (7.4/10) | — | + +## Open unknowns + +| Unknown | Cost to settle | When | +|---|---|---| +| Aspect ratio slot position | 1 capture ($0, non-default aspect) | Gate 0 | +| Count > 1 semantics (entry[4]) | 1 capture ($0, count=2) | Gate 0 | +| WAF escalation at N=10 consecutive | 10 images (~$0, Imagen) | Gate 0 | +| Direct-vs-UI latency comparison | Same N=10 run, logged | Gate 0 | +| `maseQ` direct upload for local-file I2I | Research + 1 test | Deferred | + +--- + +## Phased sequence + +### Gate 0 — WAF spike + settle unknowns (design validation) + +This gate can kill the design. Run it first, before any production code. + +- [ ] **G0.1 — WAF escalation spike.** Using the spike branch scripts, run N=10 + consecutive T2I generations via direct httpx POST against one profile. Log each + response status code, `mint_ms`, `post_ms`, `total_ms`. If Flow escalates + (429, challenge, block), document the threshold. **STOP if N<5 triggers a block.** + +- [ ] **G0.2 — Latency comparison.** In the same run, compare the N=10 direct times + against N=10 UI-transport times for the same prompt. This is the performance + case the user asked for. Record the numbers. + +- [ ] **G0.3 — Aspect ratio capture.** One generation ($0) with `--aspect 16:9`. + Diff the ogiZ0b frame against the default-aspect capture. Identify the slot. + +- [ ] **G0.4 — Count capture.** One generation ($0) with count=2. Confirm whether + entry[4] controls count. Note whether count=2 is one POST returning 2 images + or two separate POSTs. + +- [ ] **G0.5 — Write finding doc.** Consolidate all spike + Gate 0 results into + `docs/superpowers/spikes/2026-11-22-direct-image-with-browser-token.md`. + +**Gate 0 exit criteria:** WAF allows ≥5 consecutive, latency numbers recorded, +aspect and count slots identified or documented as unknowable. + +### Phase 1 — Core direct transport (T2I only) + +The smallest slice that works end-to-end: plain text-to-image with default +aspect and count=1. + +- [ ] **T1.1 — Frame builder.** `src/gflow_cli/api/transports/frame_builder.py`: + `build_ogiz0b_frame(prompt, model, project_id, recaptcha_token) -> str` — pure + function, builds the batchexecute body from scratch (12-slot minimum). No + captured templates, no file I/O. No optional parameters until their slots are + proven in Gate 0. Returns the full `f.req` form-encoded body ready for httpx. + +- [ ] **T1.2 — `can_serve()`.** A module-level function in `direct_http.py`: + `direct_can_serve(request: GenerateImageRequest) -> bool`. Returns `True` only + for plain T2I with default aspect and count≤1. Extended in Phase 2. + +- [ ] **T1.3 — DirectHttpTransport class.** + `src/gflow_cli/api/transports/direct_http.py`: implements + `FlowTransportStrategy.generate_images()`. Steps: + 1. `direct_can_serve(request)` — if false, raise `DirectTransportUnavailableError` + (the caller in `FlowApiClient` catches and routes to `ui_automation`) + 2. Acquire a `WireSession` from `flow_wire` (cookies + tokens, reusing the + existing infrastructure; add `ogiZ0b` to `_ALLOWED_RPCIDS` or factor out + the session acquisition) + 3. `page.evaluate("grecaptcha.enterprise.execute(site_key, {action})")` — the + browser `Page` comes from the existing `FlowApiClient` context + 4. `build_ogiz0b_frame(prompt, model, project_id, recaptcha_token)` + 5. httpx POST to `_BATCHEXECUTE` (reuse `flow_wire`'s headers and timeout pattern) + 6. `image_records(response)` → `list[GeneratedImage]` + 7. Download signed URLs via httpx + + The transport does NOT handle video, scene, or any non-image operation. Those + stay on `ui_automation` unconditionally. + +- [ ] **T1.4 — Transport registration.** Add `"direct_http"` to `_registry()` in + `transports/__init__.py`. Add to `EXPERIMENTAL_TRANSPORTS`. Do NOT add to + `STANDALONE_ONLY_TRANSPORTS` — it needs the FlowApiClient's browser for + reCAPTCHA minting. + +- [ ] **T1.5 — Tests (offline).** + - Frame builder: assert slot structure, project_id placement, `inner[4]` = `[uuid]` + - `can_serve`: true for plain T2I, false for refs/mentions/non-default aspect + - Transport orchestration: mocked wire session + mocked `page.evaluate` + mocked httpx + - BDD: "Given a valid profile, when I generate a T2I image with `--transport + direct_http`, then the image is generated via direct HTTP and saved to disk" + +- [ ] **T1.6 — E2E test.** `tests/e2e/test_direct_image_e2e.py`, marker `e2e_image` + ($0 tier). One T2I generation with `--transport direct_http`. Verify the asset + record's `metadata_json` contains `"transport": "direct_http"`. + +- [ ] **T1.7 — MCP parity.** The MCP `gflow_generate_image` tool calls + `generate_images()` on whatever transport is active. But the queued MCP path + goes through `FlowWorker`, which is different code from the CLI's direct call. + Add one MCP-path test that `direct_http` works through the worker. Verify the + returned schema matches the CLI path. + +### Phase 2 — Full image surface (I2I, mentions, aspect, count) + +Wire the features whose slots are now known from Gate 0. + +- [ ] **T2.1 — In-project I2I refs.** Wire `refs` parameter in the frame builder: + `entry[2] = [[media_id, null, null, null, 1], ...]` (format known from + research). Update `can_serve()` to accept requests with `reference_images`. + The `GenerateImageRequest.reference_images` already carries media IDs. + +- [ ] **T2.2 — Character mentions.** Wire `mentions` parameter: prompt doc changes + in `entry[8]` + entity IDs in `entry[10]`. Update `can_serve()`. The + `NameResolver` already resolves `@Character` to entity IDs. + +- [ ] **T2.3 — Aspect ratio.** Wire the slot discovered in G0.3. Map from the CLI's + `--aspect` values to the wire format. Update `can_serve()`. + +- [ ] **T2.4 — Count.** Wire the slot discovered in G0.4. Update `can_serve()`. + +- [ ] **T2.5 — Tests.** Unit tests for each new frame builder path. BDD scenarios: + I2I with in-project ref, character mention, non-default aspect, count=2. + One e2e test per new path (all $0 tier). + +### Phase 3 — Observability and hardening + +- [ ] **T3.1 — Telemetry.** Add `note_transport(kind: str)` to `telemetry.py` + following the `note_engine` / `note_host` pattern. Emit `("transport", + "direct")` or `("transport", "ui")` per generation. + +- [ ] **T3.2 — Structlog events.** Three events: + `direct.frame_built` (prompt hash, model, slot count), + `direct.image_post` (elapsed_ms, status_code), + `direct.fallback_to_ui` (reason). Via existing `structlog.get_logger()`. + +- [ ] **T3.3 — DataStore metadata.** Add `"transport": "direct_http"` to the + `metadata_json` dict in `data/_repo_assets.py::upsert_asset()`. No schema + migration — it is a JSON column. One line change. + +- [ ] **T3.4 — Performance fields.** Log `mint_ms`, `post_ms`, `total_ms` as + structlog fields on `direct.image_post`. These feed the comparison report + from Gate 0. + +- [ ] **T3.5 — Fallback wiring.** On HTTP 403 from the direct POST: log + `direct.fallback_to_ui`, raise `DirectTransportUnavailableError` so the + `FlowApiClient` routes to `ui_automation` for that generation. On timeout + or 5xx: raise the existing `NetworkError` — no fallback, the frame may have + been billed. + +- [ ] **T3.6 — Tests.** Fallback path test (mocked 403 → verify UI transport + invoked). Timeout test (mocked timeout → verify error, no fallback). + Performance field assertions. + +### Phase 4 — Local-file I2I via maseQ (deferred, follow-up issue) + +Local-file I2I (`--initial-frame local.png`) currently uploads via the browser. +The `maseQ` RPC is a separate upload with its own reCAPTCHA token. `can_serve()` +routes these to UI until this phase ships. + +- [ ] **T4.1 — Spike: maseQ direct upload.** +- [ ] **T4.2 — Upload module.** `upload_image_direct(file, cookies, tokens) -> media_id`. +- [ ] **T4.3 — Wire into DirectHttpTransport + update `can_serve()`.** +- [ ] **T4.4 — Tests.** + +--- + +## Concurrency, batch, and parallel execution + +Research findings from the codebase analysis: + +| Concern | Current state | Direct HTTP impact | +|---|---|---| +| **`gflow run` (batch)** | Sequential per prompt, calls `generate_images()` in a loop | Direct HTTP plugs in at the transport level — no loop changes. Each iteration mints its own reCAPTCHA token | +| **`gflow image batch`** | Sequential, same loop | Same — transport-level swap, no structural change | +| **`"ref": "batch:N"`** | In-batch cross-reference resolves to a media_id before the next generation | Works with direct HTTP — the returned `GeneratedImage` carries the media_id | +| **Local-file rows in batch** | Rows with a local `--initial-frame` need `maseQ` upload | Routes to UI via `can_serve()` until Phase 4. The batch loop already handles per-row transport decisions | +| **ProfileLease** | Per-profile, held by `FlowApiClient` | Unchanged — the browser stays open for reCAPTCHA minting, so the lease is still needed | +| **MCP per-profile lock** | `asyncio.Lock` per profile in the MCP server | Unchanged — serializes requests to the same profile | +| **Two processes, same profile** | ProfileLease prevents concurrent access | Unchanged | +| **Token minting** | `page.evaluate()` serializes naturally on one Page | One token per generation, sequential — no pooling | +| **Token expiry during long batches** | — | Tokens valid ~2 min; sequential minting per-call is fine | + +**Decision:** no structural changes to concurrency or batch. The direct transport +is a drop-in replacement at the `generate_images()` interface. The existing +serialization (ProfileLease, MCP lock, sequential batch loop) all work as-is. + +--- + +## New / touched files + +``` +src/gflow_cli/api/transports/ +├── frame_builder.py # NEW — ogiZ0b frame constructor (pure function) +├── direct_http.py # NEW — DirectHttpTransport + can_serve() +└── __init__.py # EDIT — register direct_http in _registry() + +src/gflow_cli/api/flow_wire.py # EDIT — factor out session acquisition or add ogiZ0b to allowed RPCs +src/gflow_cli/telemetry.py # EDIT — add note_transport() +src/gflow_cli/data/_repo_assets.py # EDIT — transport key in metadata_json (1 line) + +tests/ +├── transports/ +│ ├── test_frame_builder.py +│ └── test_direct_http.py +└── e2e/ + └── test_direct_image_e2e.py # e2e_image tier ($0) + +docs/ +├── superpowers/spikes/2026-11-22-direct-image-with-browser-token.md # Gate 0 findings +└── DIRECT_TRANSPORT.md # user-facing doc +``` + +No new cookie reader — reuse `auth.cookies.read_cookies_for()`. +No new token fetcher — reuse `flow_wire`'s page token scraping. +No new runtime deps — `httpx` and `sqlite3` (stdlib) are already present. + +--- + +## Risks and mitigations + +| Risk | Likelihood | Mitigation | +|---|---|---| +| WAF escalation on consecutive direct POSTs | Medium | **Gate 0** — measured before any production code | +| Cookie/PSIDTS expiry mid-batch | Low | Per-generation check; `DirectTransportUnavailableError` → route to UI | +| ogiZ0b frame format changes server-side | Medium | Frame builder is a pure function, easy to update; `image_records()` catches malformed responses | +| reCAPTCHA enterprise blocks `page.evaluate` | Low | Same mechanism the UI transport uses — if it breaks, both break | +| Double-send on billed op | High impact | Never retry a sent ogiZ0b; on timeout, raise error | +| Unsupported feature silently sent with defaults | High impact | `can_serve()` gate — route before POST, never after | +| `ImageGenerationRecord` vs `GeneratedImage` type mismatch | Medium | The direct path returns `GeneratedImage` (the DTO); verify the conversion matches what `ui_automation` returns | + +--- + +## Definition of Done + +- [ ] Gate 0 passed: WAF allows ≥5 consecutive, latency numbers recorded, aspect and count slots known. +- [ ] `gflow image t2i --transport direct_http "a cat"` generates via direct HTTP, saves to disk. +- [ ] In-project I2I (`--ref `) works via direct HTTP. +- [ ] Character mentions (`"a cat @Character"`) work via direct HTTP. +- [ ] `can_serve()` routes unsupported shapes (local-file I2I, unknown slots) to UI before POST. +- [ ] MCP `gflow_generate_image` with transport=direct_http works through the FlowWorker. +- [ ] `gflow run` (batch) works with direct_http — including `"ref": "batch:N"` cross-references. +- [ ] Telemetry records `transport: direct` / `transport: ui` in the weekly report. +- [ ] Fallback to UI on HTTP 403 is logged and works; timeout/5xx raises, no fallback. +- [ ] All quality gates: ruff, ruff format, pyright (0), pytest (≥80%), `/gflow:check`. +- [ ] E2E: `pytest -m e2e_image` passes with direct_http as the transport. +- [ ] Performance comparison: direct vs ui_automation over ≥10 runs, numbers in finding doc. +- [ ] `docs/DIRECT_TRANSPORT.md` written, indexed in `docs/INDEX.md`. +- [ ] Phase 4 (local-file I2I via maseQ) tracked as a follow-up issue. + +--- + +## Decisions + +1. **Gate 0 first.** WAF escalation is predict risk #1 and can kill the design. + Measure it before writing production code. + +2. **Reuse `flow_wire.py`.** No new cookie reader, no new token fetcher. The direct + image transport is a new RPC (`ogiZ0b`) on the existing wire infrastructure. + +3. **`can_serve()` gate.** Unsupported features route to UI before any POST. + The direct path never sends a frame it cannot fully build. + +4. **Experimental first.** Start behind `EXPERIMENTAL_TRANSPORTS` flag. Promote to + default after Gate 0 + 50 successful generations across profiles. + +5. **No local-file upload in v1.** `maseQ` is a separate RPC with its own + complexity. In-project I2I covers the common case; local-file deferred to + Phase 4 / follow-up issue. + +6. **Fallback is pre-send or definitive only.** A timeout or 5xx after the POST + is an error, not a fallback trigger — the frame may have been billed. + +7. **One reCAPTCHA token per generation.** No token pooling or pre-minting. + Sequential minting from the same page is reliable and simple. + +8. **Images only.** The direct transport implements `generate_images()` only. + Video, scene, and all other operations stay on `ui_automation` unconditionally. + `make_transport` picks one transport for the client, so the DirectHttpTransport + must delegate non-image operations to the UI transport (or the routing must + happen at the `FlowApiClient` level per-operation). + +9. **Hexagonal / DDD / Strategy pattern — no god classes.** + - The transport layer is a **port** (`FlowTransportStrategy` protocol) with + multiple **adapters** (`ui_automation`, `direct_http`, the experimentals). + Each adapter owns its own I/O; the domain (`GenerateImageRequest` → + `GeneratedImage`) stays transport-agnostic. + - The `can_serve()` gate is a **strategy selector**, not a monolith branch. + Each transport declares what it can serve; the routing layer picks the + right adapter per request. This is CQRS-adjacent: the read path (cookies, + tokens) is separated from the write path (frame build, POST). + - The frame builder is a **pure domain function** — no I/O, no state, no + browser dependency. It takes domain types in and returns wire bytes out. + - `flow_wire.py` is infrastructure — it stays behind the port boundary. + The direct transport calls it; it never calls the transport. + - No class accumulates unrelated responsibilities. If `DirectHttpTransport` + starts growing (upload, polling, download), split by responsibility along + the domain boundary, not by size. + - TDD with `/ub-mode` is the execution discipline. Failing test first, then + the smallest implementation that passes. If we hit errors: + `superpowers:systematic-debugging` — root cause before any fix attempt. + +--- + +## Execution record (2026-11-23) + +| Item | Outcome | +|---|---| +| Gate 0 | Passed: 10/10 consecutive direct POSTs; direct median 18.6 s vs UI 20.7 s; `entry[4]` is the aspect enum (1:1=1, 9:16=2, 16:9=3, 3:4=4, 4:3=5); count is N entries in one POST | +| Cookie source | The on-disk store is unreadable while Chrome holds the profile (`auth/cookies.py`), so the transport reads the live browser context; `flow_wire` supplies the shell tokens and user agent | +| Mint | `FlowApiClient`'s mint refuses the migrated host and uses the labs action, so the transport mints `IMAGE_GENERATION` itself and retries while reCAPTCHA loads | +| Model | `NARWHAL` is sent as `BELUGA` (#958); other models route to the UI transport | +| T2.1 / T2.2 | One in-project ref, or one character id with its name; both also ride as a chip in `entry[8]` | +| T3.3 | Recorded by the image recorder from `GeneratedImage.transport`, not by `upsert_asset` (which never sees the transport) | +| Live e2e | `tests/e2e/test_direct_image_e2e.py` (t2i, 16:9 x2, model routing, in-project I2I, character) and `test_direct_image_worker_e2e.py` (queued MCP path) pass on a `flow.google.com` profile | + +Not served directly yet: a bare `@Name` mention (the request carries no character id), +count 3-4, several refs or characters, local-file refs (Phase 4), batch runs (`image_batch` +calls the UI transport's batch method). The telemetry endpoint must accept the `transport` +key before a client that sends it is released. diff --git a/docs/superpowers/spikes/2026-11-22-direct-image-gate0.md b/docs/superpowers/spikes/2026-11-22-direct-image-gate0.md new file mode 100644 index 000000000..65268fb37 --- /dev/null +++ b/docs/superpowers/spikes/2026-11-22-direct-image-gate0.md @@ -0,0 +1,140 @@ +# Spike: direct HTTP image transport — Gate 0 (WAF, latency, aspect and count slots) + +**Date:** 2026-11-22 · **Profile:** `denon82` (Flow served `flow.google.com`) +· **Base:** `chore/spike-direct-image-with-browser-token` (`ee7fa2d7`) +· **Cost:** 21 images (daily image quota, zero credits); captures $0 (route-aborted) +· **Script:** [`scripts/dev/spike_direct_image_gate0.py`](../../../scripts/dev/spike_direct_image_gate0.py) +· **Plan:** [`docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md`](../plans/2026-11-22-direct-http-image-transport/PLAN.md) — Gate 0 +· **Raw evidence:** `scripts/dev/_spike_out/spike_direct_image_gate0_*.jsonl` (gitignored; tokens redacted to their length) + +## Question + +Before any production code: does Flow accept a run of consecutive direct `ogiZ0b` POSTs +built the way the transport would ship them, how does their latency compare with the UI +transport on the same profile, and which frame slots carry aspect ratio and image count? + +## Method + +One warm `FlowApiClient` on one project. Every direct POST has the shape that would ship: + +- frame built from scratch (no captured template), `inner[4] = [batch_uuid]`; +- `at` / `f.sid` / `bl` from `flow_wire._shell_tokens` (the shell GET the credits read uses); +- user agent from `flow_wire._user_agent` (the profile's Chrome major version); +- a fresh `IMAGE_GENERATION` reCAPTCHA token minted on the project page for every POST; +- one POST per generation, 120 s budget, never retried. + +The pre-registered readings are in the script's docstring. + +## Results + +### Finding 1 — the on-disk cookie store is unreadable while Chrome holds the profile + +Run 1 stopped before any POST: `auth.cookies.read_cookies_for()` raised +`CookieStoreUnreadable` with the browser open. This is the documented behaviour of that +reader (`src/gflow_cli/auth/cookies.py:333` probes the jar because Chrome holds it +exclusively on Windows). The direct transport needs the browser open to mint tokens, so +it **cannot** use the on-disk reader. Run 2 took the cookies from the live browser +context (`page.context.cookies(["https://flow.google.com"])`, 26 cookies); the first +spike had already shown Flow accepts those. + +### G0.1 — WAF escalation: none at N=10 + +| Measure | Value | +|---|---| +| Consecutive direct POSTs | 10 | +| HTTP 200 + image generated | **10 / 10** | +| RPC errors / refusals | 0 | +| Images per POST | 1 (768 x 1376, JPEG) | +| UI control run needed | no (no refusal occurred) | + +No 429, 403 or `UNUSUAL_ACTIVITY` at N=10 back-to-back on one profile. + +### G0.2 — latency, direct vs UI transport (same profile, prompt, model, project) + +| Arm | n | min | median | mean | max | +|---|---|---|---|---|---| +| Direct: mint + POST to reply | 10 | 16.7 s | **18.6 s** | 18.4 s | 21.4 s | +| — mint only | 10 | 0.12 s | 0.13 s | 0.15 s | 0.22 s | +| — download (signed URL, separate) | 10 | 0.68 s | 0.87 s | 0.87 s | 1.14 s | +| UI transport, warm: `generate_image` call to records | 10 | 19.0 s | **20.7 s** | 20.9 s | 22.9 s | + +The direct path is about **2.2 s (≈10 %) faster per warm image**. Server-side generation +dominates both arms. The arms ran back to back (direct first), not interleaved, so a +drift in Flow's own generation time between the two blocks is not excluded. The UI arm's +model is the same wire model: `NARWHAL` is sent as `BELUGA` on flow.google.com +(`_mc_common.py:535`). + +### G0.3 / G0.4 — aspect and count captures + +Four route-aborted captures ($0) of Flow's own `ogiZ0b` submit, driven through the real +UI transport on the same project (default, 16:9, count=2, default again): + +| Capture | POSTs | Entries in `inner[1]` | `entry[3]` | `entry[4]` | Other slots | +|---|---|---|---|---|---| +| default (9:16) | 1 | 1 | random int | **2** | — | +| 16:9 | 1 | 1 | random int | **3** | identical to default | +| count = 2 | 1 | **2** | a different random int per entry | 2 | identical; one shared `inner[4]` batch UUID | +| default again | 1 | 1 | random int | 2 | identical to the first | + +- **`entry[4]` is the aspect-ratio enum**, not the image count: portrait (9:16) is `2`, + 16:9 is `3`. The other three aspects (`SQUARE`, `4:3`, `3:4`) are not measured. +- **Count is the number of entries in `inner[1]`**, in ONE POST. Each entry carries its + own `entry[3]`, so that slot is per image (a seed-like value), not a session counter. +- The UI's entries carry three extra slots, `[12]`/`[13]` (two random UUIDs) and + `[14] = 4`. The 12-slot from-scratch entry is accepted without them (spike `16ab3d4b` + and the 10 POSTs above). + +A first capture run measured count = 1 for "count = 2" because it called +`generate_image`, which forces `count=1` (`_flow_generation.py:604`). The rerun above +uses `generate_images_batch`, the path that reaches Flow's x{N} selector. + +## Readings + +1. **The WAF does not escalate on 10 consecutive direct image POSTs** from one profile. + Gate 0's ≥ 5 criterion passes. +2. **Latency is a modest gain, not the case for the transport.** The case is robustness: + no selectors, no locale-sensitive DOM, no contenteditable prompt editor. +3. **Cookies come from the browser context, not the disk.** `read_cookies_for` cannot + serve this transport on Windows while the minting browser is open. +4. **`FlowApiClient`'s own mint cannot serve this transport.** `_mint_recaptcha_token` + calls `raise_if_migrated` first (`_flow_generation.py:424`) and defaults to the labs + action `imageGeneration`. The transport keeps `uses_page_owned_image_recaptcha() -> + True` and mints `IMAGE_GENERATION` on the project page itself. +5. **`flow_wire._execute_direct_rpc` cannot serve this transport.** Its 5 s total budget + is shorter than one generation, and it maps a timeout to a fallback reason, which the + plan forbids after send. The transport reuses `_shell_tokens` and `_user_agent` with + its own 120 s POST. + +6. **Phase 2 has its slots.** Aspect is `entry[4]` (two of five values measured); count + is N entries in one POST, each with its own `entry[3]`. Count > 1 on the direct path + is still unsent: whether Flow returns N images for N 12-slot entries is the first + Phase 2 measurement. + +### Phase 2 follow-up (same day, same profile and project) + +| Probe | Method | Result | +|---|---|---| +| Count = 2 on the direct path | one POST, two 12-slot entries, own `entry[3]` each | HTTP 200, **2 images**, 23.9 s | +| 16:9 on the direct path | one POST, `entry[4] = 3` | HTTP 200, **1376 x 768**, 18.0 s | +| 1:1 / 4:3 / 3:4 | route-aborted captures of Flow's submit ($0) | `entry[4]` = **1 / 5 / 4** | + +| In-project I2I (one `--ref`) | Flow's own submit, read by a passive request observer | `entry[2] = [[media_id, null, null, null, 1]]`; `entry[8]` starts with a chip `[null, [[media_id, display_name]]]`, then the text with **two** leading spaces | +| One `@Character` | the same | `entry[10] = [[entity_id]]`; `entry[8]` starts with a chip `[null, [null, null, [entity_id, name]]]`, then the text with **one** leading space | + +The referenced submits needed a passive observer: the UI transport routes its own image +submit to guard the reference, and that route runs before the spike's abort, so those two +submits reached Flow (two images, zero credits). A bare `@Name` mention resolves to the +character's name only (`reference_entity_names`); the composer picks the id in the browser. + +So the full `entry[4]` table is 1:1 = 1, 9:16 = 2, 16:9 = 3, 3:4 = 4, 4:3 = 5; 9:16 and +16:9 are proven by direct POSTs, the other three by capture only. + +**Gate 0 verdict: PASS.** WAF ≥ 5 consecutive (10/10), latency recorded, aspect and +count slots identified. + +## What was not measured + +- Escalation beyond N=10, across several profiles, or over a long batch. +- Interleaved direct/UI timing, and cold-start timing (first generation of a process). +- Whether the on-disk cookies work on macOS or Linux with Chrome open (Windows only here). +- I2I references, character mentions, non-default aspect on the direct path (Phase 2). diff --git a/scripts/dev/spike_direct_image_gate0.py b/scripts/dev/spike_direct_image_gate0.py new file mode 100644 index 000000000..e2fd8bbb4 --- /dev/null +++ b/scripts/dev/spike_direct_image_gate0.py @@ -0,0 +1,362 @@ +r"""Gate 0 for the direct HTTP image transport: WAF escalation, latency, aspect and count slots. + +Plan: docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md (Gate 0). + +The POST is the shape that would ship, not a replay: + - frame built from scratch (no captured template; ``inner[4] = [uuid]``) + - cookies from the profile's on-disk store, read WHILE Chrome holds the profile + - ``at``/``f.sid``/``bl`` from flow_wire's own shell GET (``_shell_tokens``) + - UA from ``flow_wire._user_agent`` (the profile's Chrome major version) + - a fresh ``IMAGE_GENERATION`` reCAPTCHA token minted on the page for every POST + - one POST per generation, 120 s budget, never retried (a sent ogiZ0b may be billed) +``flow_wire._execute_direct_rpc`` is NOT used: its 5 s total budget is shorter than an +image generation (16-20 s measured), and it maps a timeout to a fallback reason. + +Phases (one warm FlowApiClient, one fresh project): + G0.1 N consecutive direct POSTs. On the first non-generation, ONE UI generation runs as + a control (separates WAF escalation from the daily image cap / a profile-wide + refusal) and the direct loop stops. + G0.2 N UI-transport generations, same prompt and model (NARWHAL -> wire BELUGA), timed + on the same span as the direct arm: call -> image records. Download is timed + separately for direct and not at all for UI (generate_image does not download). + G0.3/4 route-aborted captures ($0) driven through the real UI transport: default, + 16:9, count=2, then default again to reset the sticky settings pane. Every ogiZ0b + POST is kept, so "count=2" can be read as one POST with N entries, N POSTs, or a + scalar slot. + +Cost: up to 2N+1 images (daily image quota, zero credits). Captures are $0. + +Pre-registered readings (written before the run): + | Outcome | Reading | + |-------------------------------------------|----------------------------------------------| + | 10/10 direct generated | no escalation at N=10; Gate 0 WAF passes | + | first refusal at i>=5, UI control OK | escalation threshold ~i on the direct path; | + | | passes (>=5) but the threshold is a design | + | | input (pacing / fallback) | + | first refusal at i<5, UI control OK | direct path is escalated early: STOP Gate 0 | + | refusal and the UI control also refused | profile-wide (cap / account), not the direct | + | | path: WAF question UNMEASURED, rerun later | + | disk cookie read fails with Chrome open | design finding: production cannot read the | + | | store while the browser holds it | + | HTTP 429 / 403 / UNUSUAL_ACTIVITY | WAF signal; record status + reasons verbatim | + | capture: aspect slot differs vs default | that slot carries aspect; record its values | + | capture: no ogiZ0b for a setting | unmeasured, not "no slot" | +""" + +from __future__ import annotations + +import argparse +import asyncio +import contextlib +import json +import secrets +import sys +import time +import uuid +from pathlib import Path +from typing import Any +from urllib.parse import parse_qs, urlencode + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import httpx # noqa: E402 + +from gflow_cli.api.flow_wire import _shell_tokens, _user_agent # noqa: E402 +from gflow_cli.api.image import Aspect, GenerateImageRequest, ImageRef # noqa: E402 +from gflow_cli.api.recaptcha import TokenMinter, discover_site_key # noqa: E402 +from gflow_cli.api.transports.batchexecute import ( # noqa: E402 + image_records, + parse_frames, + rpc_errors, +) +from gflow_cli.auth.cookies import read_cookies_for # noqa: E402 + +from _spike_common import ( # noqa: E402, isort: skip + build_client, + default_out_path, + resolve_profile_dir, + step, +) + +_ORIGIN = "https://flow.google.com" +_BATCHEXECUTE = f"{_ORIGIN}/_/AiSandboxAngularFrontend/data/batchexecute" +_RPCID = "ogiZ0b" +_MODEL = "BELUGA" +_ACTION = "IMAGE_GENERATION" +_PROMPT = "a lighthouse on a rocky coast under a stormy sky, ink and watercolor" + +_records: list[dict[str, Any]] = [] + + +def _log(tag: str, **data: Any) -> None: + rec = {"ts": time.strftime("%H:%M:%S"), "tag": tag, **data} + _records.append(rec) + step(tag, json.dumps(data, default=str)) + + +def _ms(t0: float) -> int: + return round((time.perf_counter() - t0) * 1000) + + +# Phase 2 probes (--direct-entries / --direct-aspect): the Gate 0 captures showed count is N +# entries in one POST (each with its own entry[3]) and aspect is entry[4] (2 = 9:16, 3 = 16:9). +_FRAME = {"entries": 1, "aspect": 2} + + +def build_frame(prompt: str, model: str, project_id: str, token: str) -> list[Any]: + """The proven from-scratch ogiZ0b payload (spike ee7fa2d7).""" + ctx: list[Any] = [None, 22, None, None, None, project_id, None, None, None, None, [token, 1]] + entries = [ + [None, None, None, 1 + secrets.randbelow(2**31 - 1), _FRAME["aspect"], model, None, + list(ctx), [[[prompt]]], None, None, None] + for _ in range(_FRAME["entries"]) + ] + return [None, entries, 1, ctx, [str(uuid.uuid4()).upper()]] + + +def _redact(node: Any) -> Any: + """Replace long strings (reCAPTCHA tokens) with their length, recursively.""" + if isinstance(node, str) and len(node) > 300: + return f"" + if isinstance(node, list): + return [_redact(x) for x in node] + return node + + +async def direct_once( + i: int, + *, + minter: TokenMinter, + project_id: str, + tokens: Any, + headers: dict[str, str], +) -> bool: + t0 = time.perf_counter() + token = await minter.mint(_ACTION) + mint_ms = _ms(t0) + payload = build_frame(_PROMPT, _MODEL, project_id, token) + body = urlencode({ + "f.req": json.dumps([[[_RPCID, json.dumps(payload, separators=(",", ":")), None, + "generic"]]]), + "at": tokens.at, + }) + query = {"rpcids": _RPCID, "source-path": f"/project/{project_id}", "bl": tokens.bl, + "f.sid": tokens.fsid, "hl": "en", "_reqid": str(1000 + secrets.randbelow(9000)), + "rt": "c"} + url = f"{_BATCHEXECUTE}?{urlencode({k: v for k, v in query.items() if v})}" + post_headers = { + **headers, + "content-type": "application/x-www-form-urlencoded;charset=UTF-8", + "x-same-domain": "1", "origin": _ORIGIN, "referer": f"{_ORIGIN}/project/{project_id}", + "sec-fetch-site": "same-origin", "sec-fetch-mode": "cors", "sec-fetch-dest": "empty", + } + t1 = time.perf_counter() + try: + async with httpx.AsyncClient(follow_redirects=False, trust_env=False, + timeout=httpx.Timeout(120.0, connect=10.0)) as hx: + resp = await hx.post(url, content=body, headers=post_headers) + except httpx.HTTPError as exc: + _log("direct", i=i, verdict="TRANSPORT_ERROR", error=type(exc).__name__, + mint_ms=mint_ms, post_ms=_ms(t1), total_ms=_ms(t0)) + return False + post_ms = _ms(t1) + errors = rpc_errors(resp.text) if resp.status_code == 200 else [] + recs = [] + if resp.status_code == 200: + for rid, data in parse_frames(resp.text): + if rid == _RPCID: + with contextlib.suppress(Exception): + recs.extend(image_records(rid, data)) + total_ms = _ms(t0) + dl: dict[str, Any] = {} + if recs and recs[0].image_url: + t2 = time.perf_counter() + async with httpx.AsyncClient(timeout=30.0, trust_env=False) as hx: + img = await hx.get(recs[0].image_url) + dl = {"dl_ms": _ms(t2), "dl_status": img.status_code, "dl_bytes": len(img.content), + "magic": img.content[:4].hex()} + _log("direct", i=i, status=resp.status_code, + verdict="GENERATED" if recs else ("REJECTED" if errors else "EMPTY"), + images=len(recs), dims=[f"{r.dimensions[0]}x{r.dimensions[1]}" for r in recs], + errors=[{"code": e.code, "reasons": list(e.reasons)} for e in errors], + head=None if recs or resp.status_code == 200 else resp.text[:300], + mint_ms=mint_ms, post_ms=post_ms, total_ms=total_ms, **dl) + return bool(recs) + + +async def ui_once(tag: str, i: int, client: Any, project_id: str, **req_kw: Any) -> bool: + t0 = time.perf_counter() + try: + img = await asyncio.wait_for( + client.generate_image(project_id=project_id, + req=GenerateImageRequest(prompt=_PROMPT, **req_kw)), + timeout=300, + ) + except Exception as exc: # noqa: BLE001 - a spike records every failure class + _log(tag, i=i, verdict="FAILED", error=type(exc).__name__, detail=str(exc)[:200], + total_ms=_ms(t0)) + return False + _log(tag, i=i, verdict="GENERATED", total_ms=_ms(t0), + dims=f"{img.dimensions[0]}x{img.dimensions[1]}", aspect=img.aspect_ratio) + return True + + +async def capture(label: str, client: Any, project_id: str, **req_kw: Any) -> None: + page = client._page # noqa: SLF001 - spike-only + bodies: list[dict[str, Any]] = [] + + async def on_route(route: Any) -> None: + req = route.request + # Run 2 measured: post_data is a strict utf-8 decode and raises on binary bodies. + data = (req.post_data_buffer or b"").decode("utf-8", errors="replace") + if _RPCID in req.url or _RPCID in data: + bodies.append({"url_rpcids": parse_qs(req.url.split("?", 1)[-1]).get("rpcids"), + "data": data}) + await route.abort() + else: + await route.continue_() + + def on_request(req: Any) -> None: + # Passive copy: when the UI transport installs its own submit route (the I2I guard), + # it runs before ours and our abort never sees the request (measured 2026-11-22). + if "batchexecute" in req.url and _RPCID in req.url: + data = (req.post_data_buffer or b"").decode("utf-8", errors="replace") + if not any(b["data"] == data for b in bodies): + bodies.append({"url_rpcids": [_RPCID], "data": data, "observed": True}) + + count = req_kw.pop("count", 1) + page.on("request", on_request) + await page.route("**/data/batchexecute**", on_route) + try: + with contextlib.suppress(Exception): + # generate_image forces count=1 (_flow_generation.py:604); the batch entry + # point is the one that reaches Flow's x{N} tab. + await asyncio.wait_for( + client.generate_images_batch( + project_id=project_id, + req=req_kw.pop("request", None) or GenerateImageRequest(prompt=_PROMPT, **req_kw), + count=count, + ), + timeout=90, + ) + finally: + await page.unroute("**/data/batchexecute**", on_route) + page.remove_listener("request", on_request) + posts = [] + for b in bodies: + freq = json.loads(parse_qs(b["data"]).get("f.req", ["null"])[0] or "null") + for call in (freq or [[]])[0]: + if call and call[0] == _RPCID: + inner = json.loads(call[1]) + posts.append(_redact(inner)) + _log("capture", label=label, count=count, request={k: str(v) for k, v in req_kw.items()}, + posts=len(posts), entries_per_post=[len(p[1]) for p in posts if isinstance(p[1], list)], + frames=posts) + + +async def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--profile", default="denon82") + ap.add_argument("--n", type=int, default=10) + ap.add_argument("--ui-n", type=int, default=10) + ap.add_argument("--skip-captures", action="store_true") + ap.add_argument("--captures-only", action="store_true", help="skip G0.1/G0.2 ($0 run)") + ap.add_argument("--project", default=None, help="reuse a project instead of creating one") + ap.add_argument("--direct-entries", type=int, default=1, help="Phase 2: entries per POST") + ap.add_argument("--direct-aspect", type=int, default=2, help="Phase 2: entry[4] value") + ap.add_argument("--capture-aspects", default="", help="Phase 2: Aspect names, comma-separated") + ap.add_argument("--capture-ref", action="store_true", help="Phase 2: capture an in-project I2I") + ap.add_argument("--capture-mention", default="", help="Phase 2: capture an @Name mention") + args = ap.parse_args() + _FRAME.update(entries=args.direct_entries, aspect=args.direct_aspect) + + profile_dir = resolve_profile_dir(args.profile) + out = default_out_path("spike_direct_image_gate0", ".jsonl") + step("OUTPUT", str(out)) + try: + async with build_client(profile_dir, headless=False) as client: + pid = args.project or ( + await client.create_project(title="gflow gate0 direct-image spike") + ).project_id + _log("project", project_id=pid) + page = client._page # noqa: SLF001 + await page.goto(f"{_ORIGIN}/project/{pid}", wait_until="networkidle", timeout=60_000) + await asyncio.sleep(2) + + # Disk cookies read WHILE Chrome holds the profile (the production condition). + # Run 1 (22:57Z) measured CookieStoreUnreadable here: Chrome holds the jar + # exclusively (cookies.py:333). The live context is the only source then. + try: + cookies = read_cookies_for(profile_dir) + _log("cookies", source="disk", count=len(cookies), with_chrome_open=True) + except Exception as exc: # noqa: BLE001 + ctx_cookies = await page.context.cookies([_ORIGIN]) + cookies = [(c["name"], c["value"]) for c in ctx_cookies] + _log("cookies", source="browser_context", disk_error=type(exc).__name__, + count=len(cookies), with_chrome_open=True) + ua = _user_agent(profile_dir) + headers = {"user-agent": ua or "", "accept-language": "en-US,en;q=0.9", + "cookie": "; ".join(f"{n}={v}" for n, v in cookies)} + async with httpx.AsyncClient(follow_redirects=False, trust_env=False, + timeout=httpx.Timeout(15.0, connect=5.0)) as hx: + tokens = await _shell_tokens(hx, profile_dir, headers) + _log("shell", at_len=len(tokens.at), fsid=bool(tokens.fsid), bl=tokens.bl, ua=ua) + + await discover_site_key(page) + minter = TokenMinter(page) + + if args.captures_only: + args.n = args.ui_n = 0 + # G0.1 — N consecutive direct POSTs, UI control on the first refusal. + for i in range(1, args.n + 1): + if not await direct_once(i, minter=minter, project_id=pid, tokens=tokens, + headers=headers): + await ui_once("ui_control", i, client, pid) + break + + # G0.2 — UI arm, same prompt/model/project. + for i in range(1, args.ui_n + 1): + await ui_once("ui", i, client, pid) + + # G0.3 / G0.4 — $0 captures through the real UI transport. + if args.capture_mention: # Phase 2 T2.2: Flow's own character-mention submit + from gflow_cli.services.mentions import resolve_and_apply + + req = await resolve_and_apply( + client, + GenerateImageRequest(prompt=f"@{args.capture_mention} on a pier at sunset"), + path="image", project_id=pid, tool_specs=(), quiet=True, + ) + _log("mention_resolved", entities=list(req.reference_entities), + names=list(req.reference_entity_names), prompt=req.prompt) + await capture("mention", client, pid, request=req) + await capture("reset_default", client, pid) + elif args.capture_ref: # Phase 2 T2.1: Flow's own in-project I2I submit frame + made = await client.generate_image( + project_id=pid, req=GenerateImageRequest(prompt=_PROMPT) + ) + _log("ref_source", media_id=made.media_name, has_display=bool(made.display_name)) + ref = ImageRef( + name=made.media_name, display_name=made.display_name or "", in_project=True + ) + await capture("i2i_in_project", client, pid, refs=(ref,)) + await capture("reset_default", client, pid) + elif args.capture_aspects: # Phase 2: the entry[4] value of each remaining aspect + for name in args.capture_aspects.split(","): + await capture(f"aspect_{name}", client, pid, aspect=Aspect[name]) + await capture("reset_default", client, pid) + elif not args.skip_captures: + await capture("default", client, pid) + await capture("aspect_16_9", client, pid, aspect=Aspect.LANDSCAPE) + await capture("count_2", client, pid, count=2) + await capture("reset_default", client, pid) + finally: + with open(out, "w", encoding="utf-8") as f: + for r in _records: + f.write(json.dumps(r, default=str) + "\n") + step("SAVED", str(out)) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/website/docs/TELEMETRY.md b/website/docs/TELEMETRY.md index 3c0637d48..eea1119b9 100644 --- a/website/docs/TELEMETRY.md +++ b/website/docs/TELEMETRY.md @@ -35,7 +35,7 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | -| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. Runs that noted no transport count as `unknown`. | +| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. A run that generated no image adds nothing to this map. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent From fb4be23f57d1f2adbefff722999eca867f5cdbeb Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 00:56:53 +0000 Subject: [PATCH 23/32] =?UTF-8?q?fix(transport):=20direct=5Fhttp=20review?= =?UTF-8?q?=20round=20=E2=80=94=20fallbacks,=20token=20cache,=20parking,?= =?UTF-8?q?=20scope?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From the code-review and ponytail-review passes, each with a regression test that fails on the previous commit: - a character name with no id is not served (it crashed after the mint); - --ui-mode agentic and refs from a local file keep the UI path; - a rejected POST drops the cached shell tokens (a stale at stuck in a long-lived worker); - connect/pool timeouts, redirects and 401 fall back: Flow accepted nothing; - the page is parked after a direct run; - NO_PROXY alone no longer disables the path; - the served host is read after navigating, so a labs.google account falls back before any POST; - each mint attempt is bounded; cookies are matched by domain (#222). The weekly transports telemetry field and its notice-version bump are taken out: the key went to every image user, and the bump stops EU/EEA uploads until re-consent. It ships with the endpoint change. Per-image metadata stays. --- CHANGELOG.md | 3 +- docs/DIRECT_TRANSPORT.md | 19 +- docs/TELEMETRY.md | 15 +- .../PLAN.md | 5 +- src/gflow_cli/api/_flow_generation.py | 4 - src/gflow_cli/api/flow_wire.py | 5 + src/gflow_cli/api/transports/direct_http.py | 339 +++++++++--------- src/gflow_cli/telemetry.py | 44 +-- tests/api/test_client_image.py | 30 -- tests/api/transports/test_direct_http.py | 197 +++++++++- tests/test_telemetry.py | 28 -- tests/test_telemetry_notice.py | 14 - website/docs/TELEMETRY.md | 15 +- 13 files changed, 415 insertions(+), 303 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f9d0e9b1..5ab19372b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one or two images, one in-project `--ref`, or one `--reference-entity` with its name; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and HTTP 403 falls back to the UI transport. -- **The weekly usage report counts the image transport used.** A new field, `transports` (`direct`, `ui`, `other`), counts image generations by transport strategy (`direct` for direct HTTP, `ui` for UI automation), and generated asset metadata records `"transport": "direct_http"` when direct transport produced the image. The privacy notice moves to version 4 and names image transport. In the EU and EEA, consent given to an earlier notice version no longer counts: uploads stop until `gflow telemetry on` is run again. +- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one or two images, one in-project `--ref`, or one `--reference-entity` with its name; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. ### Fixed diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md index 65d131db8..f923b3bbc 100644 --- a/docs/DIRECT_TRANSPORT.md +++ b/docs/DIRECT_TRANSPORT.md @@ -29,14 +29,14 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Aspect 9:16, 16:9 | yes | live generations (768x1376, 1376x768) | | Aspect 1:1, 4:3, 3:4 | yes | captures of Flow's own submit | | Count 1 or 2 | yes | a live two-image generation in one request | -| One `--ref` to an image already in the project (with its display name) | yes | a live generation | +| One `--ref` to an image already in the project (with its display name), not from a local file | yes | a live generation | | One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | | Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | | Count 3 or 4 | no | not sent directly | | Several refs, several characters, a ref plus a character | no | not captured | -| A local-file ref (`--ref ./photo.png`, needs an upload) | no | upload not ported | +| A ref that came from a local file (`--ref ./photo.png`) | no | the UI path re-uploads a missing asset; a direct request cannot | | A bare `@Name` mention | no | the request carries no character id to send | -| Agent-mode instructions | no | not captured | +| Agent-mode instructions, or `--ui-mode agentic` | no | not captured | | A configured proxy (gflow's, the environment's or the OS's) | no | the browser and the request could leave by different routes | ## Failure behaviour @@ -44,19 +44,20 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | What happens | Before the request is sent? | Result | |---|---|---| | The browser's cookies, the session tokens or the reCAPTCHA mint are unavailable | yes | the same request runs on `ui_automation` | -| The connection cannot be opened | yes | the same request runs on `ui_automation` | -| Flow answers HTTP 403 | no, but Flow refused it | the same request runs on `ui_automation` | +| The connection cannot be opened (or opening it timed out) | yes | the same request runs on `ui_automation` | +| The account is served on labs.google, or `GFLOW_CLI_FLOW_HOST=labs.google` | yes | the same request runs on `ui_automation` | +| Flow answers a redirect, HTTP 401 or HTTP 403 | no, but Flow accepted nothing | the same request runs on `ui_automation` | | A timeout, a dropped connection or any other HTTP status | no | the run stops with a network error (`next_action: reconcile`); gflow does **not** resend, because Flow may have made the image | | Flow refuses the prompt | no | the same refusal error as the UI path | -A sent request is never retried. A reCAPTCHA mint is retried for up to 10 seconds while the -page loads its reCAPTCHA script, because a mint spends nothing. +A sent request is never retried. Every rejected reply drops the cached session token, so a +stale one cannot stick in a long-running MCP server or worker. A reCAPTCHA mint is retried +for up to 10 seconds while the page loads its reCAPTCHA script, because a mint spends +nothing. The page is parked after every direct run, as after a UI run. ## What it records - Each image's catalog row carries `"transport": "direct_http"` in its `metadata_json`. -- The weekly usage report counts image generations by transport (`direct`, `ui`): see - [TELEMETRY.md](TELEMETRY.md). - Log events: `direct.frame_built`, `direct.image_post` (status, `mint_ms`, `post_ms`, `total_ms`) and `direct.fallback_to_ui` (reason). Set `GFLOW_CLI_LOG_LEVEL=INFO` to see them. Tokens, cookies, prompts and signed URLs are never logged. diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 108ce0c0b..83eecc120 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -10,7 +10,7 @@ Counters are kept in `/telemetry.db`, separately from the catalo grouped by ISO week and retained for 53 weeks. gflow counts command and flag names, outcomes, coarse duration buckets, command transitions, crash fingerprints made from exception and code names, and generation details read from the local catalog. It also records the storage service category and MCP -client category, image transport, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. +client category, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. `gflow telemetry show` prints the current week's report as JSON, including its random per-week `report_id`; this is the report sent by the uploader. `gflow data stats` shows your own local usage @@ -35,7 +35,6 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | -| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. A run that generated no image adds nothing to this map. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent @@ -83,7 +82,7 @@ read your IP address or locale to make this decision, and never sends the timezo Local counters still work in the EU/EEA and remain on your device unless you consent. To allow weekly uploads, run `gflow telemetry on`; this records your choice locally in `/telemetry.consent`, together with the notice version you agreed to. When the -notice changes (version 4 added image transport), uploads stop until you run +notice changes (version 3 added the browser engine and the Flow site), uploads stop until you run `gflow telemetry on` again. Run `gflow telemetry off` to withdraw consent and stop counting and uploads. Environment kill switches still take precedence. @@ -120,13 +119,13 @@ the sender is `src/gflow_cli/telemetry_upload.py` in this repository. ## Notice -Notice version: 4 +Notice version: 3 ```text gflow sends weekly usage totals to improve it, and we share overall figures publicly and with -sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, -error codes, and your country as a total. No ID, prompts, paths or account details. Each -report is added to totals and discarded. +sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and +your country as a total. No ID, prompts, paths or account details. Each report is added to +totals and discarded. Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0 See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` @@ -134,7 +133,7 @@ See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETR The notice shown in the EU/EEA: ```text -gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. +gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry off) See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` diff --git a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md index 2d799db03..43b2b5089 100644 --- a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -417,5 +417,6 @@ No new runtime deps — `httpx` and `sqlite3` (stdlib) are already present. Not served directly yet: a bare `@Name` mention (the request carries no character id), count 3-4, several refs or characters, local-file refs (Phase 4), batch runs (`image_batch` -calls the UI transport's batch method). The telemetry endpoint must accept the `transport` -key before a client that sends it is released. +calls the UI transport's batch method). The weekly telemetry field (T3.1) is not in this change: it went out for every +image user and needed a notice-version bump that stops EU/EEA uploads until re-consent, +so it ships together with the endpoint change. T3.3 (per-image metadata) is in. diff --git a/src/gflow_cli/api/_flow_generation.py b/src/gflow_cli/api/_flow_generation.py index 759a0ec94..7347b6fe9 100644 --- a/src/gflow_cli/api/_flow_generation.py +++ b/src/gflow_cli/api/_flow_generation.py @@ -15,7 +15,6 @@ import structlog -from gflow_cli import telemetry from gflow_cli.api import routes from gflow_cli.api._engine import ( mint_evaluate_kwargs, @@ -564,9 +563,6 @@ async def _drive_images_generation( "running the command again." ), ) from exc - telemetry.note_transport( - "direct" if any(img.transport == "direct_http" for img in images) else "ui" - ) if not images: raise ContentPolicyError( detail="empty media[]", diff --git a/src/gflow_cli/api/flow_wire.py b/src/gflow_cli/api/flow_wire.py index 7a921fa96..1f45ab9bf 100644 --- a/src/gflow_cli/api/flow_wire.py +++ b/src/gflow_cli/api/flow_wire.py @@ -274,6 +274,11 @@ async def _shell_tokens( shell_tokens = _shell_tokens +def forget_tokens(profile_dir: Path) -> None: + """Drop this profile's cached shell tokens: a rejected POST may mean a stale ``at``.""" + _tokens.pop(profile_dir, None) + + async def _read_cookies(profile_dir: Path) -> list[tuple[str, str]]: """``read_cookies_for`` on a daemon thread, bounded by ``_TOTAL_S``. diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index e5e6a6513..5a490a13e 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -10,7 +10,6 @@ from dataclasses import replace from http.cookiejar import CookieJar, DefaultCookiePolicy from typing import TYPE_CHECKING -from urllib.parse import urlencode import httpx import structlog @@ -19,11 +18,11 @@ from gflow_cli.api._engine import mint_evaluate_kwargs from gflow_cli.api.image import Model from gflow_cli.api.recaptcha import TokenMinter -from gflow_cli.api.transports._common import migrated_route +from gflow_cli.api.transports._common import flow_host_kind from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images from gflow_cli.api.transports.frame_builder import build_ogiz0b_body from gflow_cli.api.transports.ui_automation import UiAutomationTransport -from gflow_cli.config import get_settings +from gflow_cli.config import UiMode, get_settings, resolve_ui_mode from gflow_cli.errors import NetworkError, RecaptchaError if TYPE_CHECKING: @@ -41,12 +40,12 @@ # every other model routes to the UI transport until its wire name is captured. _WIRE_MODEL: dict[Model, str] = {Model.NARWHAL: "BELUGA"} - # Counts measured on the direct path (one POST with two entries returned two images). _MAX_DIRECT_COUNT = 2 _ORIGIN = "https://flow.google.com" _MINT_BUDGET_S = 10.0 # how long a freshly navigated page gets to load reCAPTCHA _MINT_RETRY_S = 0.5 +_NAVIGATE_MS = 45_000 # the composer's own budget for reaching a project _RECONCILE_HINT = ( "Flow may have accepted this image request before the error, so gflow did not resend " "it. Check the project in Flow for the new image before running the command again." @@ -56,8 +55,9 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: """True only for a request whose every wire slot is measured. - T2I with a measured model, any aspect, and up to ``_MAX_DIRECT_COUNT`` images. No - reference images, character entities, Agent instructions or ``@`` mentions yet. + T2I with a measured model, any aspect, up to ``_MAX_DIRECT_COUNT`` images, at most one + in-project reference or one named character, on the classic composer. No Agent + instructions and no ``@`` mentions. """ return ( request.model in _WIRE_MODEL @@ -67,36 +67,40 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: and not request.ref_paths and not request.instructions and "@" not in request.prompt + and resolve_ui_mode(request.ui_mode) is not UiMode.AGENTIC ) def _references_measured(request: GenerateImageRequest) -> bool: """No refs, or the one measured I2I shape: a single in-project image with a display - name (the chip needs it), one output image. A local file needs an upload first.""" + name (the chip needs it), one output image. A ref that came from a local file keeps the + UI path: there a missing asset is re-uploaded (#772), which the direct POST cannot do.""" if not request.refs: return True (ref, *more) = request.refs - return not more and ref.in_project and bool(ref.display_name) and request.count == 1 + return ( + not more + and ref.in_project + and bool(ref.display_name) + and not ref.local_path + and request.count == 1 + ) def _characters_measured(request: GenerateImageRequest) -> bool: """No character, or the one measured shape: a single entity id with its name (the chip - needs both), no image reference, one output image. A bare ``@Name`` mention carries no - id here (the UI picker resolves it in the browser), so it stays on the UI transport.""" - if not request.reference_entities: + needs both), no image reference, one output image. A bare ``@Name`` mention carries a + name but no id here (the UI picker resolves it in the browser), so it stays on the UI.""" + ids, names = request.reference_entities, request.reference_entity_names + if not ids and not names: return True - names = request.reference_entity_names return ( - len(request.reference_entities) == 1 - and len(names) == 1 - and bool(names[0]) - and not request.refs - and request.count == 1 - ) + len(ids) == 1 and len(names) == 1 and bool(names[0]) and not request.refs + ) and request.count == 1 class _DirectFallbackError(Exception): - """Internal sentinel: nothing was sent, so the UI transport may run instead.""" + """Internal sentinel: nothing was accepted, so the UI transport may run instead.""" def __init__(self, reason: str) -> None: super().__init__(reason) @@ -114,15 +118,26 @@ def _reconcile_error(detail: str, *, status: int | None = None) -> NetworkError: ) +def _proxy_configured() -> bool: + """A proxy anywhere means the browser and this request could leave by different routes. + ``NO_PROXY`` alone shows up as the ``no`` key and configures no proxy.""" + return bool(get_settings().browser_proxy) or any(k != "no" for k in flow_wire.getproxies()) + + async def _session_headers(page: Page, profile_dir: Path) -> dict[str, str]: """Read path: the live browser's cookies (the on-disk store is locked while Chrome - holds the profile) and the profile's own user agent.""" + holds the profile) and the profile's own user agent. Read without a URL filter and + matched by domain: a URL filter also drops path-scoped cookies (#222).""" try: - cookies = await page.context.cookies([_ORIGIN]) + cookies = await page.context.cookies() except Exception as exc: raise _DirectFallbackError(f"cookie_error:{type(exc).__name__}") from exc cookie_header = "; ".join( - f"{name}={value}" for c in cookies if (name := c.get("name")) and (value := c.get("value")) + f"{name}={value}" + for c in cookies + if (name := c.get("name")) + and (value := c.get("value")) + and "flow.google.com".endswith(c.get("domain", "").lstrip(".")) ) if not cookie_header: raise _DirectFallbackError("cookies_empty") @@ -147,25 +162,32 @@ async def _shell( async def _mint(page: Page, project_id: str) -> str: """The single browser step: an IMAGE_GENERATION token minted on the project page. - Right after a navigation the enterprise script is not loaded yet and the mint raises - ``RecaptchaError`` (measured 2026-11-23 on an i2i run with ``--project``). A mint spends - nothing, so it is retried until the script answers or the budget runs out. + The page must end up on flow.google.com: an account Flow serves on labs.google is + redirected there, and the direct path does not serve it. Right after a navigation the + enterprise script is not loaded yet and the mint raises ``RecaptchaError`` (measured + 2026-11-23 on an i2i run with ``--project``). A mint spends nothing, so it is retried, + every attempt bounded, until the script answers or the budget runs out. """ target = f"{_ORIGIN}/project/{project_id}" try: if not page.url.startswith(target): - await page.goto(target) - minter = TokenMinter(page, mint_evaluate_kwargs=mint_evaluate_kwargs()) - deadline = time.monotonic() + _MINT_BUDGET_S - while True: - try: - return await minter.mint("IMAGE_GENERATION") - except RecaptchaError: - if time.monotonic() >= deadline: - raise - await asyncio.sleep(_MINT_RETRY_S) + await page.goto(target, wait_until="domcontentloaded", timeout=_NAVIGATE_MS) except Exception as exc: - raise _DirectFallbackError(f"mint_failure:{type(exc).__name__}") from exc + raise _DirectFallbackError(f"navigation_failed:{type(exc).__name__}") from exc + if flow_host_kind(page.url) != "migrated": + raise _DirectFallbackError("served_labs") + minter = TokenMinter(page, mint_evaluate_kwargs=mint_evaluate_kwargs()) + deadline = time.monotonic() + _MINT_BUDGET_S + while True: + try: + remaining = max(deadline - time.monotonic(), 0.1) + return await asyncio.wait_for(minter.mint("IMAGE_GENERATION"), remaining) + except RecaptchaError as exc: + if time.monotonic() >= deadline: + raise _DirectFallbackError("mint_failure:RecaptchaError") from exc + await asyncio.sleep(_MINT_RETRY_S) + except Exception as exc: + raise _DirectFallbackError(f"mint_failure:{type(exc).__name__}") from exc def _post_request( @@ -182,8 +204,8 @@ def _post_request( } return httpx.Request( "POST", - f"{_ORIGIN}/_/AiSandboxAngularFrontend/data/batchexecute?" - f"{urlencode({k: v for k, v in query.items() if v is not None})}", + f"{_ORIGIN}/_/AiSandboxAngularFrontend/data/batchexecute", + params={k: v for k, v in query.items() if v is not None}, content=body, headers={ **headers, @@ -198,99 +220,100 @@ def _post_request( ) -async def _send_once(client: httpx.AsyncClient, request: httpx.Request) -> httpx.Response: - """Write path: exactly one send. A connect error reached nothing; anything after it may - have been billed and is never resent.""" +async def _send_once( + client: httpx.AsyncClient, request: httpx.Request, profile_dir: Path +) -> httpx.Response: + """Write path: exactly one send. + + Nothing was accepted when the connection never opened, or when Flow redirected (3xx), + refused the session (401) or the token (403): the UI transport may run instead. + Anything else after the send may have been billed and is never resent. Every rejected + reply drops the cached ``at`` so a stale one cannot stick in a long-lived process. + """ try: response = await client.send(request) - except httpx.ConnectError as exc: - raise _DirectFallbackError("connect_error") from exc + except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) as exc: + raise _DirectFallbackError(f"connect:{type(exc).__name__}") from exc except (httpx.TimeoutException, httpx.TransportError) as exc: cause = (str(exc).strip().splitlines() or [""])[0][:160] raise _reconcile_error(f"{type(exc).__name__} on an image submit ({cause})") from exc - if response.status_code == 403: - raise _DirectFallbackError("http_403") - if response.status_code != 200: - raise _reconcile_error( - f"HTTP {response.status_code} on an image submit", status=response.status_code - ) - return response - + status = response.status_code + if status == 200: + return response + flow_wire.forget_tokens(profile_dir) + if 300 <= status < 400 or status in (401, 403): + raise _DirectFallbackError(f"http_{status}") + raise _reconcile_error(f"HTTP {status} on an image submit", status=status) + + +def _client(http_transport: httpx.AsyncBaseTransport | None) -> httpx.AsyncClient: + return httpx.AsyncClient( + follow_redirects=False, + trust_env=False, # nothing env-derived (proxies, netrc) reaches this client + timeout=httpx.Timeout(120.0, connect=10.0), # a generation takes 16-24 s + cookies=CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])), + transport=http_transport, # None = httpx's default; a mock under test + ) -class DirectImageHttpRunner: - """Runs one direct image generation: read the session, mint, build, send once, parse.""" - def __init__(self, *, http_transport: httpx.AsyncBaseTransport | None = None) -> None: - self._http_transport = http_transport - - def _client(self) -> httpx.AsyncClient: - return httpx.AsyncClient( - follow_redirects=False, - trust_env=False, # nothing env-derived (proxies, netrc) reaches this client - timeout=httpx.Timeout(120.0, connect=10.0), # a generation takes 16-24 s - cookies=CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])), - transport=self._http_transport, # None = httpx's default; a mock under test +async def run_direct_images( + *, + page: Page, + profile_dir: Path, + project_id: str, + request: GenerateImageRequest, + http_transport: httpx.AsyncBaseTransport | None = None, +) -> list[GeneratedImage]: + """One direct image generation: read the session, mint, build, send once, parse.""" + started = time.perf_counter() + headers = await _session_headers(page, profile_dir) + async with _client(http_transport) as client: + tokens = await _shell(client, profile_dir, headers) + mint_started = time.perf_counter() + token = await _mint(page, project_id) + mint_ms = int((time.perf_counter() - mint_started) * 1000) + body = build_ogiz0b_body( + prompt=request.prompt, + model=_WIRE_MODEL[request.model], + project_id=project_id, + recaptcha_token=token, + at_token=tokens.at, + batch_id=str(uuid.uuid4()).upper(), + entry_seeds=tuple(1 + secrets.randbelow(2**31 - 1) for _ in range(request.count)), + aspect=request.aspect, + references=tuple((ref.name, ref.display_name) for ref in request.refs), + characters=tuple( + zip(request.reference_entities, request.reference_entity_names, strict=True) + ), ) - - async def run( - self, - *, - page: Page, - profile_dir: Path, - project_id: str, - request: GenerateImageRequest, - ) -> list[GeneratedImage]: - started = time.perf_counter() - headers = await _session_headers(page, profile_dir) - async with self._client() as client: - tokens = await _shell(client, profile_dir, headers) - mint_started = time.perf_counter() - token = await _mint(page, project_id) - mint_ms = int((time.perf_counter() - mint_started) * 1000) - body = build_ogiz0b_body( - prompt=request.prompt, - model=_WIRE_MODEL[request.model], - project_id=project_id, - recaptcha_token=token, - at_token=tokens.at, - batch_id=str(uuid.uuid4()).upper(), - entry_seeds=tuple(1 + secrets.randbelow(2**31 - 1) for _ in range(request.count)), - aspect=request.aspect, - references=tuple((ref.name, ref.display_name) for ref in request.refs), - characters=tuple( - zip(request.reference_entities, request.reference_entity_names, strict=True) - ), - ) - log.info( - "direct.frame_built", - model=request.model.value, - prompt_length=len(request.prompt), - count=request.count, - ) - post_started = time.perf_counter() - response = await _send_once(client, _post_request(project_id, tokens, headers, body)) log.info( - "direct.image_post", - status=response.status_code, - mint_ms=mint_ms, - post_ms=int((time.perf_counter() - post_started) * 1000), - total_ms=int((time.perf_counter() - started) * 1000), + "direct.frame_built", + model=request.model.value, + prompt_length=len(request.prompt), + count=request.count, + ) + post_started = time.perf_counter() + response = await _send_once( + client, _post_request(project_id, tokens, headers, body), profile_dir ) - images = ogiz0b_reply_images(response.text, request) - return [replace(img, transport="direct_http") for img in images] + log.info( + "direct.image_post", + status=response.status_code, + mint_ms=mint_ms, + post_ms=int((time.perf_counter() - post_started) * 1000), + total_ms=int((time.perf_counter() - started) * 1000), + ) + images = ogiz0b_reply_images(response.text, request) + return [replace(img, transport="direct_http") for img in images] class DirectHttpTransport(UiAutomationTransport): - """Direct HTTP transport for image generation with reCAPTCHA minting from Flow page.""" + """The UI transport, with measured image requests sent as one direct ``ogiZ0b`` POST.""" name = "direct_http" _profile_dir: Path | None = None - def __init__( - self, - *, - http_transport: httpx.AsyncBaseTransport | None = None, - ) -> None: + def __init__(self, *, http_transport: httpx.AsyncBaseTransport | None = None) -> None: super().__init__() self._http_transport = http_transport @@ -305,61 +328,47 @@ async def generate_images( request: GenerateImageRequest, name_resolver: Callable[[str], str | None] | None = None, ) -> list[GeneratedImage]: - """Generate images via direct HTTP when eligible, falling back to UI automation.""" + """Generate via one direct POST when the request is measured; otherwise, or when + nothing was accepted, through the inherited UI path.""" if not self._setup_done or self._page is None: msg = "DirectHttpTransport.setup() must be called before generate_images()" raise RuntimeError(msg) async with self._generate_lock: await self.park_deferred_page() + page, profile_dir = self._page, self._profile_dir + reason = self._why_not_direct(request, project_id) + if reason is None and project_id is not None and profile_dir is not None: + try: + images = await run_direct_images( + page=page, + profile_dir=profile_dir, + project_id=project_id, + request=request, + http_transport=self._http_transport, + ) + except _DirectFallbackError as fb: + reason = fb.reason + else: + self.last_image_route = "migrated" + return images + finally: + # Never leave a mounted composer for the next request (_park_composer_page). + await self._park_composer_page(page, event="direct.page_park_failed") + log.info("direct.fallback_to_ui", reason=reason) + return await self._generate_images_locked( + request, project_id=project_id, name_resolver=name_resolver + ) - if not direct_can_serve(request): - log.info("direct.fallback_to_ui", reason="unsupported_shape") - return await self._generate_images_locked( - request, project_id=project_id, name_resolver=name_resolver - ) - - if project_id is None: - log.info("direct.fallback_to_ui", reason="no_project") - return await self._generate_images_locked( - request, project_id=project_id, name_resolver=name_resolver - ) - - page = self._page - profile_dir = self._profile_dir - if profile_dir is None: - log.info("direct.fallback_to_ui", reason="no_profile_dir") - return await self._generate_images_locked( - request, project_id=project_id, name_resolver=name_resolver - ) - - flow_host = get_settings().flow_host - route = migrated_route(page.url, flow_host, prefer_migrated=True) - if route != "migrated": - log.info("direct.fallback_to_ui", reason="route_not_migrated") - return await self._generate_images_locked( - request, project_id=project_id, name_resolver=name_resolver - ) - - if get_settings().browser_proxy or flow_wire.getproxies(): - log.info("direct.fallback_to_ui", reason="proxy_configured") - return await self._generate_images_locked( - request, project_id=project_id, name_resolver=name_resolver - ) - - runner = DirectImageHttpRunner(http_transport=self._http_transport) - - try: - images = await runner.run( - page=page, - profile_dir=profile_dir, - project_id=project_id, - request=request, - ) - self.last_image_route = "migrated" - return images - except _DirectFallbackError as fb: - log.info("direct.fallback_to_ui", reason=fb.reason) - return await self._generate_images_locked( - request, project_id=project_id, name_resolver=name_resolver - ) + def _why_not_direct(self, request: GenerateImageRequest, project_id: str | None) -> str | None: + if not direct_can_serve(request): + return "unsupported_shape" + if project_id is None: + return "no_project" + if self._profile_dir is None: + return "no_profile_dir" + if get_settings().flow_host == "labs.google": + return "flow_host_labs" + if _proxy_configured(): + return "proxy_configured" + return None diff --git a/src/gflow_cli/telemetry.py b/src/gflow_cli/telemetry.py index ae4a3fbd4..b9dce9692 100644 --- a/src/gflow_cli/telemetry.py +++ b/src/gflow_cli/telemetry.py @@ -53,22 +53,22 @@ def _debug(event: str, **kw: str) -> None: OFF_FILE = "telemetry.off" CONSENT_FILE = "telemetry.consent" SCHEMA = 1 -NOTICE_VERSION = 4 +NOTICE_VERSION = 3 NOTICE_TEXT = ( "gflow sends weekly usage totals to improve it, and we share overall figures publicly and " "with\n" - "sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used,\n" - "error codes, and your country as a total. No ID, prompts, paths or account details. Each\n" - "report is added to totals and discarded.\n" + "sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and\n" + "your country as a total. No ID, prompts, paths or account details. Each report is added to\n" + "totals and discarded.\n" "Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0\n" "See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY" ) NOTICE_TEXT_CONSENT = ( "gflow can send weekly usage totals to help improve it; overall figures are shared publicly " "and " - "with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site " - "used, error codes, and your country as a total. No ID, prompts, paths or account details. " - "Each report is added to totals and discarded.\n" + "with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, " + "and your country as a total. No ID, prompts, paths or account details. Each report is " + "added to totals and discarded.\n" "In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry " "off)\n" "See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY" @@ -450,7 +450,6 @@ def _connect(home: Path) -> sqlite3.Connection: _RUN_FACTS: ContextVar[dict[str, str] | None] = ContextVar("gflow_run_facts", default=None) _ENGINES = frozenset({"playwright", "patchright"}) _HOSTS = {"labs": "labs", "migrated": "flow"} -_TRANSPORTS = frozenset({"direct", "ui"}) def _facts() -> dict[str, str]: @@ -480,23 +479,14 @@ def note_host(kind: str | None) -> None: _facts()["host"] = _HOSTS[kind] -def note_transport(kind: str) -> None: - """Note the image transport used (closed enum: direct, ui; anything else is ``other``).""" - _facts()["transport"] = kind if kind in _TRANSPORTS else "other" - - def _take_run_facts() -> list[tuple[str, str]]: """The noted facts as counter keys, cleared so the next run starts empty.""" facts = _facts() noted = dict(facts) # snapshot, then clear: a concurrent clear cannot raise here facts.clear() # a host noted without a launch must not carry into a later run - out: list[tuple[str, str]] = [] - if "engine" in noted: - out.append(("engine", noted["engine"])) - out.append(("host", noted.get("host", "unknown"))) - if "transport" in noted: - out.append(("transport", noted["transport"])) - return out + if "engine" not in noted: + return [] + return [("engine", noted["engine"]), ("host", noted.get("host", "unknown"))] def flush_run_facts(surface: Literal["cli", "mcp"]) -> None: @@ -943,7 +933,6 @@ def _report_counter_targets() -> dict[str, Any]: "mcp_clients": {}, "engines": {}, "hosts": {}, - "transports": {}, "tools": tools, "nested": {"flag": flags, "exit": exits, "duration": durations, "tool": tools}, } @@ -990,15 +979,8 @@ def _add_scalar_counter( elif kind == "crash": values = targets["crashes"].setdefault(surface, {}) values[key] = values.get(key, 0) + count - elif kind in ("client", "engine", "host", "transport"): - values = targets[ - { - "client": "mcp_clients", - "engine": "engines", - "host": "hosts", - "transport": "transports", - }[kind] - ] + elif kind in ("client", "engine", "host"): + values = targets[{"client": "mcp_clients", "engine": "engines", "host": "hosts"}[kind]] values[key] = values.get(key, 0) + count @@ -1123,5 +1105,5 @@ def build_report(week: str) -> dict[str, object]: "crashes": counters["crashes"], "tools": counters["tools"], # Sent only when non-empty: an endpoint older than #1326 rejects the keys. - **{k: counters[k] for k in ("engines", "hosts", "transports") if counters[k]}, + **{k: counters[k] for k in ("engines", "hosts") if counters[k]}, } diff --git a/tests/api/test_client_image.py b/tests/api/test_client_image.py index 2a3f14626..73aa7f053 100644 --- a/tests/api/test_client_image.py +++ b/tests/api/test_client_image.py @@ -24,7 +24,6 @@ import pytest import structlog -from gflow_cli import telemetry from gflow_cli.api.client import FlowApiClient, FlowApiError from gflow_cli.api.dto import GeneratedImage from gflow_cli.api.image import Aspect, GenerateImageRequest @@ -1016,32 +1015,3 @@ async def test_a_redirect_off_an_allowed_host_is_refused_and_nothing_is_written( _make_image(fife_url="https://flow.google.com/asb/opaque=s0"), out ) assert not out.exists() - - -class TestImageGenerationTransportTelemetry: - async def test_notes_direct_transport_when_image_has_direct_http( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - noted: list[str] = [] - monkeypatch.setattr(telemetry, "note_transport", noted.append) - img = dataclasses.replace(_make_image(), transport="direct_http") - transport = _FakeTransport([img]) - client = _client_with_transport(tmp_path, transport) - - await client.generate_image(project_id="proj-1", req=_make_req()) - - assert noted == ["direct"] - - async def test_notes_ui_transport_when_image_has_no_transport( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - noted: list[str] = [] - monkeypatch.setattr(telemetry, "note_transport", noted.append) - img = _make_image() - assert img.transport is None - transport = _FakeTransport([img]) - client = _client_with_transport(tmp_path, transport) - - await client.generate_image(project_id="proj-1", req=_make_req()) - - assert noted == ["ui"] diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index bc35b18ec..d1145ba67 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import json from dataclasses import replace from pathlib import Path @@ -107,7 +108,8 @@ def _valid_ogiz0b_text() -> str: def _make_fake_page(url: str = "https://flow.google.com/project/proj-123") -> MagicMock: page = MagicMock() page.url = url - page.goto = AsyncMock() + # Like Playwright: a goto moves page.url (the served host is read after navigating). + page.goto = AsyncMock(side_effect=lambda target, **_: setattr(page, "url", target)) page.context = MagicMock() page.context.cookies = AsyncMock(return_value=[{"name": "SID", "value": "test_sid"}]) return page @@ -529,7 +531,11 @@ def handler(request: httpx.Request) -> httpx.Response: transport._http_transport = httpx.MockTransport(handler) req = GenerateImageRequest(prompt="a blue cup") await transport.generate_images(project_id="proj-123", request=req) - transport._page.goto.assert_awaited_once_with("https://flow.google.com/project/proj-123") + # The first navigation is the mint's; the park after the run is the second. + assert ( + transport._page.goto.await_args_list[0].args[0] + == "https://flow.google.com/project/proj-123" + ) @pytest.mark.asyncio @@ -816,3 +822,190 @@ def handler(request: httpx.Request) -> httpx.Response: req = GenerateImageRequest(prompt="x", **_SKIPPER) # type: ignore[arg-type] await transport.generate_images(project_id="proj-123", request=req) assert builder.call_args.kwargs["characters"] == (("entity-1", "Skipper"),) + + +# --- Review fix round (code-review xhigh + ponytail-review xhigh, 2026-11-23) ---------- + + +def _shell_and(post: httpx.Response | Exception) -> httpx.MockTransport: + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + if isinstance(post, Exception): + raise post + return post + + return httpx.MockTransport(handler) + + +def _watch_ui(transport: DirectHttpTransport) -> list[bool]: + calls: list[bool] = [] + + async def ui(*_: Any, **__: Any) -> list[GeneratedImage]: + calls.append(True) + return [] + + transport._generate_images_locked = ui # type: ignore[method-assign] + return calls + + +def test_a_character_name_without_an_id_is_not_served() -> None: + """CR-A: names with no ids crashed in zip(strict=True) after the mint.""" + req = GenerateImageRequest(prompt="x", reference_entity_names=("Bob",)) + assert direct_can_serve(req) is False + + +def test_agentic_ui_mode_is_not_served() -> None: + """PR-4: --ui-mode agentic would have been sent as a classic frame.""" + from gflow_cli.config import UiMode + + assert direct_can_serve(GenerateImageRequest(prompt="x", ui_mode=UiMode.AGENTIC)) is False + + +def test_a_reference_from_a_local_file_keeps_the_ui_path() -> None: + """CR-I: the UI re-uploads a missing local-file asset (#772); a direct POST cannot.""" + ref = replace(_IN_PROJECT, local_path="face.png", local_sha256="0" * 64) + assert direct_can_serve(GenerateImageRequest(prompt="x", refs=(ref,))) is False + + +@pytest.mark.asyncio +async def test_a_rejected_post_drops_the_cached_shell_tokens( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + """CR-B: a stale at stuck in a long-lived process failed every later direct job.""" + transport._http_transport = _shell_and(httpx.Response(500)) + _watch_ui(transport) + with pytest.raises(NetworkError): + await transport.generate_images( + project_id="proj-123", request=GenerateImageRequest(prompt="x") + ) + assert transport._profile_dir not in flow_wire._tokens + + +@pytest.mark.asyncio +@pytest.mark.parametrize("exc", [httpx.ConnectTimeout("t"), httpx.PoolTimeout("t")]) +async def test_a_connection_that_never_opened_falls_back( + transport: DirectHttpTransport, mock_mint_and_body: None, exc: Exception +) -> None: + """CR-D: ConnectTimeout is not a ConnectError; nothing was sent, so no reconcile.""" + transport._http_transport = _shell_and(exc) + ui = _watch_ui(transport) + await transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")) + assert ui == [True] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [302, 401]) +async def test_a_redirect_or_401_falls_back_instead_of_reconcile( + transport: DirectHttpTransport, mock_mint_and_body: None, status: int +) -> None: + """CR-J: Flow accepted nothing; telling the user to check for an image was wrong.""" + transport._http_transport = _shell_and(httpx.Response(status)) + ui = _watch_ui(transport) + await transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")) + assert ui == [True] + + +@pytest.mark.asyncio +async def test_the_page_is_parked_after_a_direct_run( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + """CR-E / PR-3: a mounted composer must not leak into the next request.""" + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + park = AsyncMock() + transport._park_composer_page = park # type: ignore[method-assign] + await transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")) + park.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_no_proxy_alone_does_not_disable_the_direct_path( + transport: DirectHttpTransport, mock_mint_and_body: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """CR-F: getproxies() returns a 'no' key when only NO_PROXY is set.""" + monkeypatch.setattr(flow_wire, "getproxies", lambda: {"no": "localhost"}) + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + ui = _watch_ui(transport) + images = await transport.generate_images( + project_id="proj-123", request=GenerateImageRequest(prompt="x") + ) + assert ui == [] + assert images[0].transport == "direct_http" + + +@pytest.mark.asyncio +async def test_an_account_served_labs_falls_back_before_any_post( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + """CR-G: under flow_host=auto the old route check passed every URL.""" + page = transport._page + assert page is not None + page.url = "about:blank" + page.goto = AsyncMock( + side_effect=lambda *_a, **_k: setattr(page, "url", "https://labs.google/fx/tools/flow") + ) + posts: list[bool] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "POST": + posts.append(True) + return httpx.Response(200, text='"SNlM0e":"at-x","FdrFJe":"sid"') + + transport._http_transport = httpx.MockTransport(handler) + ui = _watch_ui(transport) + await transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")) + assert ui == [True] + assert posts == [] + + +@pytest.mark.asyncio +async def test_a_mint_that_never_settles_is_bounded( + transport: DirectHttpTransport, mock_mint_and_body: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """CR-K: one evaluate whose promise never settles hung while holding the lock.""" + monkeypatch.setattr("gflow_cli.api.transports.direct_http._MINT_BUDGET_S", 0.2) + + async def never(*_: Any, **__: Any) -> str: + await asyncio.sleep(3600) + return "" + + monkeypatch.setattr("gflow_cli.api.recaptcha.TokenMinter.mint", never) + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + ui = _watch_ui(transport) + await asyncio.wait_for( + transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")), + timeout=5, + ) + assert ui == [True] + + +@pytest.mark.asyncio +async def test_cookies_are_matched_by_domain_not_by_a_url_filter( + transport: DirectHttpTransport, mock_mint_and_body: None +) -> None: + """CR-L: a URL filter also drops path-scoped cookies (#222).""" + page = transport._page + assert page is not None + page.context.cookies = AsyncMock( + return_value=[ + {"name": "SID", "value": "a", "domain": ".google.com", "path": "/"}, + {"name": "XS", "value": "b", "domain": "flow.google.com", "path": "/_/"}, + {"name": "OTHER", "value": "c", "domain": "example.com", "path": "/"}, + ] + ) + sent: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + sent.append(request.headers.get("cookie", "")) + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + return httpx.Response(200, text=_valid_ogiz0b_text()) + + transport._http_transport = httpx.MockTransport(handler) + await transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")) + assert sent[-1] == "SID=a; XS=b" + page.context.cookies.assert_awaited_once_with() diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index f8e87466d..18933ee3d 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -333,34 +333,6 @@ def test_an_engine_outside_the_enum_is_other_and_facts_reset_per_command(tmp_hom assert report["hosts"] == {"labs": 1} -def test_a_transport_run_counts_its_transport_once(tmp_home: Path) -> None: - telemetry.note_transport("direct") - telemetry.record("cli", "image t2i", [], "0", 3.0) - report = _report() - assert report["transports"] == {"direct": 1} - - -def test_a_transport_ui_counts_ui(tmp_home: Path) -> None: - telemetry.note_transport("ui") - telemetry.record("cli", "image t2i", [], "0", 3.0) - report = _report() - assert report["transports"] == {"ui": 1} - - -def test_a_transport_outside_the_enum_is_other(tmp_home: Path) -> None: - telemetry.note_transport("custom-grpc") - telemetry.record("cli", "image t2i", [], "0", 3.0) - report = _report() - assert report["transports"] == {"other": 1} - - -def test_an_unlisted_transport_counts_other(tmp_home: Path) -> None: - telemetry.note_transport("direct_http") # a raw transport name never reaches the totals - telemetry.record("cli", "image t2i", [], "0", 3.0) - report = _report() - assert report["transports"] == {"other": 1} - - def test_the_worker_flushes_a_queued_job_s_facts(tmp_home: Path) -> None: telemetry.note_engine("playwright") telemetry.note_host("migrated") diff --git a/tests/test_telemetry_notice.py b/tests/test_telemetry_notice.py index 55b0f6789..20fe304fe 100644 --- a/tests/test_telemetry_notice.py +++ b/tests/test_telemetry_notice.py @@ -511,17 +511,3 @@ def test_consent_to_an_earlier_notice_is_not_consent( assert telemetry.consent_at() is None # v2 wrote a bare timestamp telemetry.set_consent() assert telemetry.consent_at() is not None - - -def test_consent_to_v3_notice_is_not_consent_for_v4( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A v3 consent must be renewed now that notice v4 names image transport.""" - home = tmp_path / "gflow_home" - home.mkdir(exist_ok=True) - monkeypatch.setenv("GFLOW_CLI_HOME", str(home)) - monkeypatch.setattr(telemetry, "consent_region", lambda: True) - (home / telemetry.CONSENT_FILE).write_text("2026-11-01T00:00:00+00:00\n3", encoding="utf-8") - assert telemetry.consent_at() is None - telemetry.set_consent() - assert telemetry.consent_at() is not None diff --git a/website/docs/TELEMETRY.md b/website/docs/TELEMETRY.md index eea1119b9..cf689fe5f 100644 --- a/website/docs/TELEMETRY.md +++ b/website/docs/TELEMETRY.md @@ -10,7 +10,7 @@ Counters are kept in `/telemetry.db`, separately from the catalo grouped by ISO week and retained for 53 weeks. gflow counts command and flag names, outcomes, coarse duration buckets, command transitions, crash fingerprints made from exception and code names, and generation details read from the local catalog. It also records the storage service category and MCP -client category, image transport, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. +client category, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. `gflow telemetry show` prints the current week's report as JSON, including its random per-week `report_id`; this is the report sent by the uploader. `gflow data stats` shows your own local usage @@ -35,7 +35,6 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | -| `transports` | Counts of image generations by transport: `direct` (direct HTTP), `ui` (UI automation), or `other`. A run that generated no image adds nothing to this map. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent @@ -83,7 +82,7 @@ read your IP address or locale to make this decision, and never sends the timezo Local counters still work in the EU/EEA and remain on your device unless you consent. To allow weekly uploads, run `gflow telemetry on`; this records your choice locally in `/telemetry.consent`, together with the notice version you agreed to. When the -notice changes (version 4 added image transport), uploads stop until you run +notice changes (version 3 added the browser engine and the Flow site), uploads stop until you run `gflow telemetry on` again. Run `gflow telemetry off` to withdraw consent and stop counting and uploads. Environment kill switches still take precedence. @@ -120,13 +119,13 @@ the sender is `src/gflow_cli/telemetry_upload.py` in this repository. ## Notice -Notice version: 4 +Notice version: 3 ```text gflow sends weekly usage totals to improve it, and we share overall figures publicly and with -sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, -error codes, and your country as a total. No ID, prompts, paths or account details. Each -report is added to totals and discarded. +sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and +your country as a total. No ID, prompts, paths or account details. Each report is added to +totals and discarded. Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0 See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` @@ -134,7 +133,7 @@ See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETR The notice shown in the EU/EEA: ```text -gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. +gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry off) See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` From 419b2a8a2d004b1bd13725f49e2629a06e15666c Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 01:10:13 +0000 Subject: [PATCH 24/32] fix(transport): serve catalogued in-project refs again; cover local-file i2i live The review round refused any ref with a local_path, but the CLI fills it for every catalogued image, generated ones too, so every in-project i2i went to the UI (caught by the live e2e). Adds the live local-file i2i e2e: the upload runs on the UI transport, the generation goes direct. Documents the deleted- reference case (not measured: the trash RPC refused the id) and one observed WAF refusal that did not repeat. --- docs/DIRECT_TRANSPORT.md | 12 ++++++-- src/gflow_cli/api/transports/direct_http.py | 13 +++----- tests/api/transports/test_direct_http.py | 7 +++-- tests/e2e/test_direct_image_e2e.py | 33 +++++++++++++++++++++ 4 files changed, 51 insertions(+), 14 deletions(-) diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md index f923b3bbc..87e5bdb4d 100644 --- a/docs/DIRECT_TRANSPORT.md +++ b/docs/DIRECT_TRANSPORT.md @@ -29,12 +29,12 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Aspect 9:16, 16:9 | yes | live generations (768x1376, 1376x768) | | Aspect 1:1, 4:3, 3:4 | yes | captures of Flow's own submit | | Count 1 or 2 | yes | a live two-image generation in one request | -| One `--ref` to an image already in the project (with its display name), not from a local file | yes | a live generation | +| One `--ref` to an image already in the project (with its display name) | yes | a live generation | +| One `--ref ./photo.png` (a local file) | yes, after the upload | the upload runs on the UI transport, then the generation goes direct; a live generation | | One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | | Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | | Count 3 or 4 | no | not sent directly | | Several refs, several characters, a ref plus a character | no | not captured | -| A ref that came from a local file (`--ref ./photo.png`) | no | the UI path re-uploads a missing asset; a direct request cannot | | A bare `@Name` mention | no | the request carries no character id to send | | Agent-mode instructions, or `--ui-mode agentic` | no | not captured | | A configured proxy (gflow's, the environment's or the OS's) | no | the browser and the request could leave by different routes | @@ -49,6 +49,7 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Flow answers a redirect, HTTP 401 or HTTP 403 | no, but Flow accepted nothing | the same request runs on `ui_automation` | | A timeout, a dropped connection or any other HTTP status | no | the run stops with a network error (`next_action: reconcile`); gflow does **not** resend, because Flow may have made the image | | Flow refuses the prompt | no | the same refusal error as the UI path | +| A referenced image was deleted in Flow | no | **not measured**: the UI path re-uploads the local copy (#772); the direct path reports the error and does not | A sent request is never retried. Every rejected reply drops the cached session token, so a stale one cannot stick in a long-running MCP server or worker. A reCAPTCHA mint is retried @@ -62,6 +63,13 @@ nothing. The page is parked after every direct run, as after a UI run. `total_ms`) and `direct.fallback_to_ui` (reason). Set `GFLOW_CLI_LOG_LEVEL=INFO` to see them. Tokens, cookies, prompts and signed URLs are never logged. +## Refusals observed + +On 2026-11-23 one direct run on the test profile ended in a WAF refusal (exit 10, +`WafRejectionError`) after about 25 direct generations that day; the same request two +minutes later went through. Which request drew it was not isolated. Flow refused it before +generating, so nothing was billed, and gflow did not resend it. + ## Speed Measured on one profile, ten generations each, same prompt and model: the direct path took diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 5a490a13e..b39317aa7 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -73,18 +73,13 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: def _references_measured(request: GenerateImageRequest) -> bool: """No refs, or the one measured I2I shape: a single in-project image with a display - name (the chip needs it), one output image. A ref that came from a local file keeps the - UI path: there a missing asset is re-uploaded (#772), which the direct POST cannot do.""" + name (the chip needs it), one output image. A local file is uploaded first (on the UI + transport) and arrives here as such a ref. local_path is not a signal: the CLI fills it + for every catalogued image, generated ones too.""" if not request.refs: return True (ref, *more) = request.refs - return ( - not more - and ref.in_project - and bool(ref.display_name) - and not ref.local_path - and request.count == 1 - ) + return not more and ref.in_project and bool(ref.display_name) and request.count == 1 def _characters_measured(request: GenerateImageRequest) -> bool: diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index d1145ba67..9076dccbc 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -864,10 +864,11 @@ def test_agentic_ui_mode_is_not_served() -> None: assert direct_can_serve(GenerateImageRequest(prompt="x", ui_mode=UiMode.AGENTIC)) is False -def test_a_reference_from_a_local_file_keeps_the_ui_path() -> None: - """CR-I: the UI re-uploads a missing local-file asset (#772); a direct POST cannot.""" +def test_a_catalogued_reference_with_a_local_copy_is_still_served() -> None: + """The CLI fills local_path for EVERY catalogued image, generated ones too: refusing a + ref with a local copy sent every in-project i2i to the UI (live e2e, 2026-11-23).""" ref = replace(_IN_PROJECT, local_path="face.png", local_sha256="0" * 64) - assert direct_can_serve(GenerateImageRequest(prompt="x", refs=(ref,))) is False + assert direct_can_serve(GenerateImageRequest(prompt="x", refs=(ref,))) is True @pytest.mark.asyncio diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index c4cdaa1cd..39d0a5d19 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -175,3 +175,36 @@ def test_a_named_character_is_generated_by_the_direct_transport( assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" _saved(tmp_path / "pier.jpg") assert _image_transports(e2e_env)[-1] == "direct_http" + + +def test_a_local_file_reference_is_uploaded_then_generated_directly( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + """--ref ./file: the upload runs on the UI transport, then the generation goes direct.""" + first = _t2i(e2e_env, tmp_path / "local.jpg") + assert first.returncode == 0, f"gflow image t2i failed (exit {first.returncode})" + with sqlite3.connect(e2e_env["GFLOW_CLI_DB_PATH"]) as db: + (project_id,) = db.execute("SELECT flow_project_id FROM assets").fetchone() + proc = subprocess.run( + [ + sys.executable, + "-m", + "gflow_cli", + "image", + "i2i", + "the same scene in winter", + "--ref", + str(_saved(tmp_path / "local.jpg")), + "--project", + project_id, + "--out-file", + str(tmp_path / "winter.jpg"), + ], + capture_output=True, + text=True, + check=False, + env=e2e_env | {"GFLOW_CLI_TRANSPORT": "direct_http"}, + ) + assert proc.returncode == 0, f"gflow image i2i failed (exit {proc.returncode})" + _saved(tmp_path / "winter.jpg") + assert _image_transports(e2e_env)[-1] == "direct_http" From 1e9f67923e1e347a2c1a29c99c3b630a237f72a6 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 01:18:04 +0000 Subject: [PATCH 25/32] feat(transport): serve a bare @Name mention on the direct path A mention reaches the transport as the character's name alone. Its id is read from the project's own reply (migrated_character.read_project, which also lands the page on the project for the mint); anything but exactly one character with that name falls back before any POST. Live e2e included. --- CHANGELOG.md | 2 +- docs/DIRECT_TRANSPORT.md | 3 +- .../PLAN.md | 4 +- src/gflow_cli/api/transports/direct_http.py | 45 ++++++++-- tests/api/transports/test_direct_http.py | 84 +++++++++++++++++-- tests/e2e/test_direct_image_e2e.py | 57 +++++++++++++ 6 files changed, 176 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ab19372b..bb97a0e10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one or two images, one in-project `--ref`, or one `--reference-entity` with its name; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. +- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one or two images, one in-project or local-file `--ref`, or one character (`--reference-entity` with its name, or an `@Name` mention); any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. ### Fixed diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md index 87e5bdb4d..1180cd197 100644 --- a/docs/DIRECT_TRANSPORT.md +++ b/docs/DIRECT_TRANSPORT.md @@ -32,10 +32,11 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | One `--ref` to an image already in the project (with its display name) | yes | a live generation | | One `--ref ./photo.png` (a local file) | yes, after the upload | the upload runs on the UI transport, then the generation goes direct; a live generation | | One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | +| One `@Name` mention of a character in the project | yes, when exactly one character has that name | the id is read from the project; a live generation | | Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | | Count 3 or 4 | no | not sent directly | | Several refs, several characters, a ref plus a character | no | not captured | -| A bare `@Name` mention | no | the request carries no character id to send | +| A mention whose name matches no character, or several | no | the UI picker decides | | Agent-mode instructions, or `--ui-mode agentic` | no | not captured | | A configured proxy (gflow's, the environment's or the OS's) | no | the browser and the request could leave by different routes | diff --git a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md index 43b2b5089..51f733ac5 100644 --- a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -415,8 +415,8 @@ No new runtime deps — `httpx` and `sqlite3` (stdlib) are already present. | T3.3 | Recorded by the image recorder from `GeneratedImage.transport`, not by `upsert_asset` (which never sees the transport) | | Live e2e | `tests/e2e/test_direct_image_e2e.py` (t2i, 16:9 x2, model routing, in-project I2I, character) and `test_direct_image_worker_e2e.py` (queued MCP path) pass on a `flow.google.com` profile | -Not served directly yet: a bare `@Name` mention (the request carries no character id), -count 3-4, several refs or characters, local-file refs (Phase 4), batch runs (`image_batch` +A bare `@Name` mention is served: the id is read from the project's own reply. +Not served directly yet: count 3-4, several refs or characters, local-file refs (Phase 4), batch runs (`image_batch` calls the UI transport's batch method). The weekly telemetry field (T3.1) is not in this change: it went out for every image user and needed a notice-version bump that stops EU/EEA uploads until re-consent, so it ships together with the endpoint change. T3.3 (per-image metadata) is in. diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index b39317aa7..84f37ac01 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -21,6 +21,7 @@ from gflow_cli.api.transports._common import flow_host_kind from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images from gflow_cli.api.transports.frame_builder import build_ogiz0b_body +from gflow_cli.api.transports.migrated_character import read_project from gflow_cli.api.transports.ui_automation import UiAutomationTransport from gflow_cli.config import UiMode, get_settings, resolve_ui_mode from gflow_cli.errors import NetworkError, RecaptchaError @@ -83,15 +84,44 @@ def _references_measured(request: GenerateImageRequest) -> bool: def _characters_measured(request: GenerateImageRequest) -> bool: - """No character, or the one measured shape: a single entity id with its name (the chip - needs both), no image reference, one output image. A bare ``@Name`` mention carries a - name but no id here (the UI picker resolves it in the browser), so it stays on the UI.""" + """No character, or the one measured shape: a single named character, no image + reference, one output image. A bare ``@Name`` mention arrives as the name alone; the + direct path looks its id up in the project before sending (:func:`_resolve_character`).""" ids, names = request.reference_entities, request.reference_entity_names if not ids and not names: return True return ( - len(ids) == 1 and len(names) == 1 and bool(names[0]) and not request.refs - ) and request.count == 1 + len(ids) <= 1 + and len(names) == 1 + and bool(names[0]) + and not request.refs + and request.count == 1 + ) + + +async def _resolve_character( + page: Page, project_id: str, request: GenerateImageRequest +) -> tuple[tuple[str, str], ...]: + """Read path: the ``(entity_id, name)`` pair the frame carries. + + A request with the id already has it. A bare mention carries only the name: the id is + read from Flow's own project reply (``read_project``, which also lands the page on the + project for the mint). Anything but exactly one character with that exact name falls + back before any POST, as the UI picker would refuse it. + """ + names = request.reference_entity_names + if not names: + return () + if request.reference_entities: + return ((request.reference_entities[0], names[0]),) + try: + project = await read_project(page, project_id) + except Exception as exc: + raise _DirectFallbackError(f"character_read:{type(exc).__name__}") from exc + matches = [c.entity_id for c in project.characters if c.display_name == names[0]] + if len(matches) != 1: + raise _DirectFallbackError(f"character_matches:{len(matches)}") + return ((matches[0], names[0]),) class _DirectFallbackError(Exception): @@ -264,6 +294,7 @@ async def run_direct_images( headers = await _session_headers(page, profile_dir) async with _client(http_transport) as client: tokens = await _shell(client, profile_dir, headers) + characters = await _resolve_character(page, project_id, request) mint_started = time.perf_counter() token = await _mint(page, project_id) mint_ms = int((time.perf_counter() - mint_started) * 1000) @@ -277,9 +308,7 @@ async def run_direct_images( entry_seeds=tuple(1 + secrets.randbelow(2**31 - 1) for _ in range(request.count)), aspect=request.aspect, references=tuple((ref.name, ref.display_name) for ref in request.refs), - characters=tuple( - zip(request.reference_entities, request.reference_entity_names, strict=True) - ), + characters=characters, ) log.info( "direct.frame_built", diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 9076dccbc..82891d32e 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -787,7 +787,7 @@ def test_direct_can_serve_one_named_character() -> None: @pytest.mark.parametrize( "kwargs", [ - {"reference_entities": ("entity-1",)}, # a bare @Name mention: no name pair here + {"reference_entities": ("entity-1",)}, # an id with no name: the chip needs both {"reference_entities": ("entity-1",), "reference_entity_names": ("",)}, { "reference_entities": ("entity-1", "entity-2"), @@ -851,12 +851,6 @@ async def ui(*_: Any, **__: Any) -> list[GeneratedImage]: return calls -def test_a_character_name_without_an_id_is_not_served() -> None: - """CR-A: names with no ids crashed in zip(strict=True) after the mint.""" - req = GenerateImageRequest(prompt="x", reference_entity_names=("Bob",)) - assert direct_can_serve(req) is False - - def test_agentic_ui_mode_is_not_served() -> None: """PR-4: --ui-mode agentic would have been sent as a classic frame.""" from gflow_cli.config import UiMode @@ -1010,3 +1004,79 @@ def handler(request: httpx.Request) -> httpx.Response: await transport.generate_images(project_id="proj-123", request=GenerateImageRequest(prompt="x")) assert sent[-1] == "SID=a; XS=b" page.context.cookies.assert_awaited_once_with() + + +# --- A bare @Name mention (T2.2): the name is resolved to the project's character id ----- + + +def _project_with(*names: str) -> Any: + from gflow_cli.api.character import Character + from gflow_cli.api.transports.migrated_character import ProjectRead + + chars = tuple( + Character( + entity_id=f"entity-{i}", + display_name=name, + project_id="proj-123", + workflow_ids=(), + voice=None, + personality=None, + thumbnail_media_id=None, + ) + for i, name in enumerate(names) + ) + return ProjectRead(characters=chars, voices=()) + + +def test_a_bare_mention_name_is_served() -> None: + req = GenerateImageRequest(prompt="Skipper on a pier", reference_entity_names=("Skipper",)) + assert direct_can_serve(req) is True + + +@pytest.mark.asyncio +async def test_a_bare_mention_is_resolved_to_the_project_character_id( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + builder = MagicMock(return_value="f.req=mock_body&at=at-x&") + monkeypatch.setattr("gflow_cli.api.transports.direct_http.build_ogiz0b_body", builder) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.read_project", + AsyncMock(return_value=_project_with("Mate", "Skipper")), + ) + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + req = GenerateImageRequest(prompt="Skipper on a pier", reference_entity_names=("Skipper",)) + images = await transport.generate_images(project_id="proj-123", request=req) + assert builder.call_args.kwargs["characters"] == (("entity-1", "Skipper"),) + assert images[0].transport == "direct_http" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("names", [(), ("Skipper", "Skipper")]) +async def test_a_mention_with_no_or_several_matches_falls_back_before_any_post( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, names: tuple[str, ...] +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.read_project", + AsyncMock(return_value=_project_with(*names)), + ) + posts: list[bool] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "POST": + posts.append(True) + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + + transport._http_transport = httpx.MockTransport(handler) + ui = _watch_ui(transport) + req = GenerateImageRequest(prompt="Skipper on a pier", reference_entity_names=("Skipper",)) + await transport.generate_images(project_id="proj-123", request=req) + assert ui == [True] + assert posts == [] diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index 39d0a5d19..13bfc27b8 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -208,3 +208,60 @@ def test_a_local_file_reference_is_uploaded_then_generated_directly( assert proc.returncode == 0, f"gflow image i2i failed (exit {proc.returncode})" _saved(tmp_path / "winter.jpg") assert _image_transports(e2e_env)[-1] == "direct_http" + + +@pytest.mark.skipif( + os.environ.get("GFLOW_CLI_E2E_RUN_CHARACTER") != "1", + reason="creates a Flow character (one image generation, zero credits); opt in with " + "GFLOW_CLI_E2E_RUN_CHARACTER=1", +) +def test_a_bare_mention_is_generated_by_the_direct_transport( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + """T2.2: "@Name ..." reaches the transport as the name alone; its id is read from the + project and the image goes direct.""" + first = _t2i(e2e_env, tmp_path / "face.jpg") + assert first.returncode == 0, f"gflow image t2i failed (exit {first.returncode})" + with sqlite3.connect(e2e_env["GFLOW_CLI_DB_PATH"]) as db: + (project_id,) = db.execute("SELECT flow_project_id FROM assets").fetchone() + made = subprocess.run( + [ + sys.executable, + "-m", + "gflow_cli", + "character", + "create", + "--project", + project_id, + "--name", + "Bosun", + "--image", + str(_saved(tmp_path / "face.jpg")), + ], + capture_output=True, + text=True, + check=False, + env=e2e_env, + ) + assert made.returncode == 0, f"gflow character create failed (exit {made.returncode})" + proc = subprocess.run( + [ + sys.executable, + "-m", + "gflow_cli", + "image", + "t2i", + "@Bosun on a pier at sunset", + "--project", + project_id, + "--out-file", + str(tmp_path / "pier.jpg"), + ], + capture_output=True, + text=True, + check=False, + env=e2e_env | {"GFLOW_CLI_TRANSPORT": "direct_http"}, + ) + assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" + _saved(tmp_path / "pier.jpg") + assert _image_transports(e2e_env)[-1] == "direct_http" From ed7689ed62b82c757ca24a03f77d9b56973672d5 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 01:21:41 +0000 Subject: [PATCH 26/32] feat(transport): serve every image count Flow offers on the direct path One POST with 3 and 4 entries returned 3 and 4 images live, so the direct path's own cap of 2 goes; GenerateImageRequest already bounds count to 1-4. References and characters stay at count 1, the only shape measured. --- CHANGELOG.md | 2 +- docs/DIRECT_TRANSPORT.md | 3 +-- .../2026-11-22-direct-http-image-transport/PLAN.md | 2 +- src/gflow_cli/api/transports/direct_http.py | 10 ++++------ tests/api/transports/test_direct_http.py | 7 ++++--- tests/e2e/test_direct_image_e2e.py | 10 +++++----- 6 files changed, 16 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb97a0e10..0c4f86d22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one or two images, one in-project or local-file `--ref`, or one character (`--reference-entity` with its name, or an `@Name` mention); any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. +- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one in-project or local-file `--ref`, or one character (`--reference-entity` with its name, or an `@Name` mention); any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. ### Fixed diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md index 1180cd197..53090bd04 100644 --- a/docs/DIRECT_TRANSPORT.md +++ b/docs/DIRECT_TRANSPORT.md @@ -28,13 +28,12 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Text-to-image, model `nano2` / `nano21` (sent as `BELUGA`) | yes | 10 consecutive live generations | | Aspect 9:16, 16:9 | yes | live generations (768x1376, 1376x768) | | Aspect 1:1, 4:3, 3:4 | yes | captures of Flow's own submit | -| Count 1 or 2 | yes | a live two-image generation in one request | +| Count 1 to 4 | yes | live generations: 2, 3 and 4 entries in one request returned 2, 3 and 4 images | | One `--ref` to an image already in the project (with its display name) | yes | a live generation | | One `--ref ./photo.png` (a local file) | yes, after the upload | the upload runs on the UI transport, then the generation goes direct; a live generation | | One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | | One `@Name` mention of a character in the project | yes, when exactly one character has that name | the id is read from the project; a live generation | | Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | -| Count 3 or 4 | no | not sent directly | | Several refs, several characters, a ref plus a character | no | not captured | | A mention whose name matches no character, or several | no | the UI picker decides | | Agent-mode instructions, or `--ui-mode agentic` | no | not captured | diff --git a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md index 51f733ac5..2a3de12ba 100644 --- a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -416,7 +416,7 @@ No new runtime deps — `httpx` and `sqlite3` (stdlib) are already present. | Live e2e | `tests/e2e/test_direct_image_e2e.py` (t2i, 16:9 x2, model routing, in-project I2I, character) and `test_direct_image_worker_e2e.py` (queued MCP path) pass on a `flow.google.com` profile | A bare `@Name` mention is served: the id is read from the project's own reply. -Not served directly yet: count 3-4, several refs or characters, local-file refs (Phase 4), batch runs (`image_batch` +Count 1-4 is served (N entries returned N images live). Not served directly yet: several refs or characters, local-file refs (Phase 4), batch runs (`image_batch` calls the UI transport's batch method). The weekly telemetry field (T3.1) is not in this change: it went out for every image user and needed a notice-version bump that stops EU/EEA uploads until re-consent, so it ships together with the endpoint change. T3.3 (per-image metadata) is in. diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 84f37ac01..a06716582 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -41,8 +41,6 @@ # every other model routes to the UI transport until its wire name is captured. _WIRE_MODEL: dict[Model, str] = {Model.NARWHAL: "BELUGA"} -# Counts measured on the direct path (one POST with two entries returned two images). -_MAX_DIRECT_COUNT = 2 _ORIGIN = "https://flow.google.com" _MINT_BUDGET_S = 10.0 # how long a freshly navigated page gets to load reCAPTCHA _MINT_RETRY_S = 0.5 @@ -56,13 +54,13 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: """True only for a request whose every wire slot is measured. - T2I with a measured model, any aspect, up to ``_MAX_DIRECT_COUNT`` images, at most one - in-project reference or one named character, on the classic composer. No Agent - instructions and no ``@`` mentions. + T2I with a measured model, any aspect, any count Flow offers (1-4: N entries in one + POST returned N images live), or one in-project reference or one named character with + one image, on the classic composer. No Agent instructions and no raw ``@`` left in the + prompt (a mention reaches here already resolved to a name). """ return ( request.model in _WIRE_MODEL - and request.count <= _MAX_DIRECT_COUNT and _references_measured(request) and _characters_measured(request) and not request.ref_paths diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 82891d32e..cad65414f 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -39,8 +39,10 @@ def test_direct_can_serve_every_measured_aspect(aspect: Aspect) -> None: assert direct_can_serve(GenerateImageRequest(prompt="x", aspect=aspect)) is True -def test_direct_can_serve_two_images() -> None: - assert direct_can_serve(GenerateImageRequest(prompt="x", count=2)) is True +@pytest.mark.parametrize("count", [1, 2, 3, 4]) +def test_direct_can_serve_every_count_flow_offers(count: int) -> None: + """One entry per image in one POST: 2, 3 and 4 entries returned 2, 3 and 4 images live.""" + assert direct_can_serve(GenerateImageRequest(prompt="x", count=count)) is True @pytest.mark.parametrize( @@ -49,7 +51,6 @@ def test_direct_can_serve_two_images() -> None: {"refs": (ImageRef(name="00000000-0000-0000-0000-000000000001"),)}, {"ref_paths": (Path("image.png"),)}, {"reference_entities": ("entity-1",)}, - {"count": 3}, # only count <= 2 is measured on the direct path {"instructions": (AgentInstruction(text="keep lighting dark"),)}, {"prompt": "A photo of @Alice in wonderland"}, ], diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index 13bfc27b8..86a61402d 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -1,7 +1,7 @@ """Live E2E for the direct_http image transport (T1.6, T2.3, T2.4). A plain text-to-image run on ``GFLOW_CLI_TRANSPORT=direct_http`` is generated by one -direct ``ogiZ0b`` POST and recorded with ``metadata_json.transport = "direct_http"``; two +direct ``ogiZ0b`` POST and recorded with ``metadata_json.transport = "direct_http"``; three 16:9 images come from one direct POST; a model with no measured wire name is routed to the UI transport before any POST and still generates. All image runs: daily quota, zero credits. @@ -73,15 +73,15 @@ def test_plain_t2i_is_generated_by_the_direct_transport( assert _image_transports(e2e_env) == ["direct_http"] -def test_two_landscape_images_come_from_one_direct_post( +def test_three_landscape_images_come_from_one_direct_post( e2e_env: RedactedEnv, tmp_path: Path ) -> None: - proc = _t2i(e2e_env, tmp_path / "wide.jpg", "--aspect", "16:9", "-n", "2") + proc = _t2i(e2e_env, tmp_path / "wide.jpg", "--aspect", "16:9", "-n", "3") assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" files = sorted(p for p in tmp_path.iterdir() if p.name.startswith("wide")) - assert len(files) == 2, files + assert len(files) == 3, files assert all(p.read_bytes().startswith(_JPEG_OR_PNG) for p in files) - assert _image_transports(e2e_env) == ["direct_http", "direct_http"] + assert _image_transports(e2e_env) == ["direct_http"] * 3 def test_a_model_with_no_measured_wire_name_routes_to_the_ui_transport( From 1e4cca294a4e203c4b8760fbf9a7d280766bde8b Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 01:27:52 +0000 Subject: [PATCH 27/32] fix(transport): match Flow cookies per RFC 6265; address CodeRabbit on #1442 - Cookies sent on the direct path are matched with auth.cookies' RFC 6265 domain rule: endswith() also accepted .le.com, le.com and an empty domain. Tests carry suffix-colliding cookies; fakes carry domains. - The unsupported-shape test uses an unserved model and fails on any HTTP call, so it tests selection; the labs-route test uses 'labs.google'. - Docs state the one-image limit for refs and characters, and that a redirect/401/403 is followed by a second, UI-driven submit. - Plan link points at the Gate 0 findings in this branch. - Spike: keep the generation record when the download fails, pin the UI arms to ui_automation, count each captured request once, state the quota cost of --capture-ref / --capture-mention. --- CHANGELOG.md | 2 +- docs/DIRECT_TRANSPORT.md | 6 ++--- .../PLAN.md | 2 +- scripts/dev/spike_direct_image_gate0.py | 26 ++++++++++++------- src/gflow_cli/api/transports/direct_http.py | 3 ++- src/gflow_cli/auth/cookies.py | 3 +++ tests/api/transports/test_direct_http.py | 23 +++++++++------- .../test_direct_http_transport_steps.py | 4 ++- 8 files changed, 44 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c4f86d22..aa653350f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one in-project or local-file `--ref`, or one character (`--reference-entity` with its name, or an `@Name` mention); any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. +- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one in-project or local-file `--ref`, or one character (`--reference-entity` with its name, or an `@Name` mention), each with one image; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. ### Fixed diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md index 53090bd04..32e59feab 100644 --- a/docs/DIRECT_TRANSPORT.md +++ b/docs/DIRECT_TRANSPORT.md @@ -29,12 +29,12 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Aspect 9:16, 16:9 | yes | live generations (768x1376, 1376x768) | | Aspect 1:1, 4:3, 3:4 | yes | captures of Flow's own submit | | Count 1 to 4 | yes | live generations: 2, 3 and 4 entries in one request returned 2, 3 and 4 images | -| One `--ref` to an image already in the project (with its display name) | yes | a live generation | +| One `--ref` to an image already in the project (with its display name), one image | yes | a live generation | | One `--ref ./photo.png` (a local file) | yes, after the upload | the upload runs on the UI transport, then the generation goes direct; a live generation | | One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | | One `@Name` mention of a character in the project | yes, when exactly one character has that name | the id is read from the project; a live generation | | Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | -| Several refs, several characters, a ref plus a character | no | not captured | +| Several refs, several characters, a ref plus a character, or a ref or character with count 2-4 | no | not captured | | A mention whose name matches no character, or several | no | the UI picker decides | | Agent-mode instructions, or `--ui-mode agentic` | no | not captured | | A configured proxy (gflow's, the environment's or the OS's) | no | the browser and the request could leave by different routes | @@ -46,7 +46,7 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | The browser's cookies, the session tokens or the reCAPTCHA mint are unavailable | yes | the same request runs on `ui_automation` | | The connection cannot be opened (or opening it timed out) | yes | the same request runs on `ui_automation` | | The account is served on labs.google, or `GFLOW_CLI_FLOW_HOST=labs.google` | yes | the same request runs on `ui_automation` | -| Flow answers a redirect, HTTP 401 or HTTP 403 | no, but Flow accepted nothing | the same request runs on `ui_automation` | +| Flow answers a redirect, HTTP 401 or HTTP 403 | no: it was sent once and refused | the request is submitted a second time, through `ui_automation`'s own page | | A timeout, a dropped connection or any other HTTP status | no | the run stops with a network error (`next_action: reconcile`); gflow does **not** resend, because Flow may have made the image | | Flow refuses the prompt | no | the same refusal error as the UI path | | A referenced image was deleted in Flow | no | **not measured**: the UI path re-uploads the local copy (#772); the direct path reports the error and does not | diff --git a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md index 2a3de12ba..5303a5fc9 100644 --- a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -4,7 +4,7 @@ **Branch:** `feature/direct-http-image-transport` (off `develop`) **Spike evidence:** `chore/spike-direct-image-with-browser-token` — 5 commits proving each component end-to-end. Findings doc: -[`docs/superpowers/spikes/2026-11-22-direct-image-with-browser-token.md`](../spikes/2026-11-22-direct-image-with-browser-token.md) +[`docs/superpowers/spikes/2026-11-22-direct-image-gate0.md`](../../spikes/2026-11-22-direct-image-gate0.md) Gate 0 findings: [`docs/superpowers/spikes/2026-11-22-direct-image-gate0.md`](../../spikes/2026-11-22-direct-image-gate0.md). ## Goal diff --git a/scripts/dev/spike_direct_image_gate0.py b/scripts/dev/spike_direct_image_gate0.py index e2fd8bbb4..38e1f0e05 100644 --- a/scripts/dev/spike_direct_image_gate0.py +++ b/scripts/dev/spike_direct_image_gate0.py @@ -49,6 +49,7 @@ import asyncio import contextlib import json +import os import secrets import sys import time @@ -172,10 +173,13 @@ async def direct_once( dl: dict[str, Any] = {} if recs and recs[0].image_url: t2 = time.perf_counter() - async with httpx.AsyncClient(timeout=30.0, trust_env=False) as hx: - img = await hx.get(recs[0].image_url) - dl = {"dl_ms": _ms(t2), "dl_status": img.status_code, "dl_bytes": len(img.content), - "magic": img.content[:4].hex()} + try: # a failed download must not lose the record of a generation that happened + async with httpx.AsyncClient(timeout=30.0, trust_env=False) as hx: + img = await hx.get(recs[0].image_url) + dl = {"dl_ms": _ms(t2), "dl_status": img.status_code, + "dl_bytes": len(img.content), "magic": img.content[:4].hex()} + except httpx.HTTPError as exc: + dl = {"dl_ms": _ms(t2), "dl_error": type(exc).__name__} _log("direct", i=i, status=resp.status_code, verdict="GENERATED" if recs else ("REJECTED" if errors else "EMPTY"), images=len(recs), dims=[f"{r.dimensions[0]}x{r.dimensions[1]}" for r in recs], @@ -211,8 +215,10 @@ async def on_route(route: Any) -> None: # Run 2 measured: post_data is a strict utf-8 decode and raises on binary bodies. data = (req.post_data_buffer or b"").decode("utf-8", errors="replace") if _RPCID in req.url or _RPCID in data: - bodies.append({"url_rpcids": parse_qs(req.url.split("?", 1)[-1]).get("rpcids"), - "data": data}) + # The request event fires before interception, so on_request may hold it already. + if not any(b["data"] == data for b in bodies): + bodies.append({"url_rpcids": parse_qs(req.url.split("?", 1)[-1]).get("rpcids"), + "data": data}) await route.abort() else: await route.continue_() @@ -261,13 +267,13 @@ async def main() -> None: ap.add_argument("--n", type=int, default=10) ap.add_argument("--ui-n", type=int, default=10) ap.add_argument("--skip-captures", action="store_true") - ap.add_argument("--captures-only", action="store_true", help="skip G0.1/G0.2 ($0 run)") + ap.add_argument("--captures-only", action="store_true", help="skip G0.1/G0.2 (route-aborted captures cost $0; --capture-ref/--capture-mention spend image quota)") ap.add_argument("--project", default=None, help="reuse a project instead of creating one") ap.add_argument("--direct-entries", type=int, default=1, help="Phase 2: entries per POST") ap.add_argument("--direct-aspect", type=int, default=2, help="Phase 2: entry[4] value") ap.add_argument("--capture-aspects", default="", help="Phase 2: Aspect names, comma-separated") - ap.add_argument("--capture-ref", action="store_true", help="Phase 2: capture an in-project I2I") - ap.add_argument("--capture-mention", default="", help="Phase 2: capture an @Name mention") + ap.add_argument("--capture-ref", action="store_true", help="Phase 2: capture an in-project I2I (spends 2 images of daily quota: a source image, and the referenced submit reaches Flow)") + ap.add_argument("--capture-mention", default="", help="Phase 2: capture an @Name mention (spends 1 image: the referenced submit reaches Flow)") args = ap.parse_args() _FRAME.update(entries=args.direct_entries, aspect=args.direct_aspect) @@ -275,6 +281,8 @@ async def main() -> None: out = default_out_path("spike_direct_image_gate0", ".jsonl") step("OUTPUT", str(out)) try: + # The UI arms and captures must drive the UI transport whatever GFLOW_CLI_TRANSPORT says. + os.environ["GFLOW_CLI_TRANSPORT"] = "ui_automation" async with build_client(profile_dir, headless=False) as client: pid = args.project or ( await client.create_project(title="gflow gate0 direct-image spike") diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index a06716582..26cde1edd 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -23,6 +23,7 @@ from gflow_cli.api.transports.frame_builder import build_ogiz0b_body from gflow_cli.api.transports.migrated_character import read_project from gflow_cli.api.transports.ui_automation import UiAutomationTransport +from gflow_cli.auth.cookies import sent_to_flow_host from gflow_cli.config import UiMode, get_settings, resolve_ui_mode from gflow_cli.errors import NetworkError, RecaptchaError @@ -160,7 +161,7 @@ async def _session_headers(page: Page, profile_dir: Path) -> dict[str, str]: for c in cookies if (name := c.get("name")) and (value := c.get("value")) - and "flow.google.com".endswith(c.get("domain", "").lstrip(".")) + and sent_to_flow_host(c.get("domain", "")) ) if not cookie_header: raise _DirectFallbackError("cookies_empty") diff --git a/src/gflow_cli/auth/cookies.py b/src/gflow_cli/auth/cookies.py index d97c9731f..faad829f5 100644 --- a/src/gflow_cli/auth/cookies.py +++ b/src/gflow_cli/auth/cookies.py @@ -309,6 +309,9 @@ def _domain_match(domain: str) -> bool: return _WIRE_HOST == domain +sent_to_flow_host = _domain_match + + def read_cookies_for(profile_dir: Path) -> list[tuple[str, str]]: """The (name, value) pairs a browser on this profile sends on ``GET https://flow.google.com/``. diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index cad65414f..f58926f68 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -112,7 +112,9 @@ def _make_fake_page(url: str = "https://flow.google.com/project/proj-123") -> Ma # Like Playwright: a goto moves page.url (the served host is read after navigating). page.goto = AsyncMock(side_effect=lambda target, **_: setattr(page, "url", target)) page.context = MagicMock() - page.context.cookies = AsyncMock(return_value=[{"name": "SID", "value": "test_sid"}]) + page.context.cookies = AsyncMock( + return_value=[{"name": "SID", "value": "test_sid", "domain": ".google.com", "path": "/"}] + ) return page @@ -183,13 +185,11 @@ async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: async def test_direct_http_unsupported_shape_falls_back_to_ui( transport: DirectHttpTransport, mock_mint_and_body: None ) -> None: - post_count = 0 + calls: list[str] = [] def handler(request: httpx.Request) -> httpx.Response: - nonlocal post_count - if request.method == "POST": - post_count += 1 - return httpx.Response(200, text=_valid_ogiz0b_text()) + calls.append(request.method) # any request at all means selection came too late + raise AssertionError(f"unexpected {request.method} {request.url}") transport._http_transport = httpx.MockTransport(handler) ui_called = False @@ -201,11 +201,12 @@ async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: transport._generate_images_locked = mock_ui_locked # type: ignore[method-assign] - req = GenerateImageRequest(prompt="a blue cup", count=2) + # A model with no measured wire name: refused by the selector, before any HTTP work. + req = GenerateImageRequest(prompt="a blue cup", model=Model.GEM_PIX_2) await transport.generate_images(project_id="proj-123", request=req) assert ui_called - assert post_count == 0 + assert calls == [] @pytest.mark.asyncio @@ -483,7 +484,7 @@ async def mock_ui_locked(*args: Any, **kwargs: Any) -> list[GeneratedImage]: async def test_direct_http_route_not_migrated_falls_back( transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, mock_mint_and_body: None ) -> None: - monkeypatch.setattr(get_settings(), "flow_host", "labs") + monkeypatch.setattr(get_settings(), "flow_host", "labs.google") transport._page.url = "https://labs.google/fx/tools/flow" ui_called = False @@ -989,6 +990,10 @@ async def test_cookies_are_matched_by_domain_not_by_a_url_filter( {"name": "SID", "value": "a", "domain": ".google.com", "path": "/"}, {"name": "XS", "value": "b", "domain": "flow.google.com", "path": "/_/"}, {"name": "OTHER", "value": "c", "domain": "example.com", "path": "/"}, + # Suffix collisions a plain endswith() would accept (RFC 6265 5.1.3 refuses them). + {"name": "SUFFIX", "value": "d", "domain": ".le.com", "path": "/"}, + {"name": "HOSTONLY", "value": "e", "domain": "le.com", "path": "/"}, + {"name": "EMPTY", "value": "f", "domain": "", "path": "/"}, ] ) sent: list[str] = [] diff --git a/tests/features/test_direct_http_transport_steps.py b/tests/features/test_direct_http_transport_steps.py index 0c05d764b..db47204a3 100644 --- a/tests/features/test_direct_http_transport_steps.py +++ b/tests/features/test_direct_http_transport_steps.py @@ -80,7 +80,9 @@ def handler(request: httpx.Request) -> httpx.Response: page.url = "https://flow.google.com/project/proj-bdd-1" page.goto = AsyncMock() page.context = MagicMock() - page.context.cookies = AsyncMock(return_value=[{"name": "SID", "value": "test_sid"}]) + page.context.cookies = AsyncMock( + return_value=[{"name": "SID", "value": "test_sid", "domain": ".google.com", "path": "/"}] + ) t = make_transport("direct_http") assert isinstance(t, DirectHttpTransport) From 1b73233c27e3a80421a920d18c45c0e06fdf7646 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 01:52:33 +0000 Subject: [PATCH 28/32] fix(transport): verify refs and characters before a direct POST (second review round) - A --ref found in the local catalog stays on the UI path: the catalog may be stale and only the UI proves the image still exists (refusing at $0). Refs made in this run (a gflow run batch:N row, a fresh upload) carry no local_path and still go direct. - A character is checked against the project's own reply for both forms: an --reference-entity id must be one the project holds (its chip uses Flow's name for it); a bare @Name matches by the picker's rule (trimmed, case-insensitive, unique). The read is bounded at 15 s. - e2e: a catalogued ref routes to the UI; gflow run with batch:0 goes direct; the local-file test uploads a freshly drawn file. - Docs: gflow run rows go direct; gflow image batch is refused on every transport; WAF refusals observed under a day's high volume. --- CHANGELOG.md | 2 +- docs/DIRECT_TRANSPORT.md | 26 +++-- .../PLAN.md | 4 +- scripts/dev/spike_direct_image_gate0.py | 10 +- src/gflow_cli/api/transports/direct_http.py | 51 ++++++--- tests/api/transports/test_direct_http.py | 102 +++++++++++++++++- tests/e2e/test_direct_image_e2e.py | 59 ++++++++-- 7 files changed, 211 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa653350f..11c22d68c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one in-project or local-file `--ref`, or one character (`--reference-entity` with its name, or an `@Name` mention), each with one image; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. +- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one ref made in this run (a `gflow run` `"ref": "batch:N"` or a newly uploaded file), or one character (`--reference-entity` with its name, or an `@Name` mention), each with one image; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. ### Fixed diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md index 32e59feab..c06e218e5 100644 --- a/docs/DIRECT_TRANSPORT.md +++ b/docs/DIRECT_TRANSPORT.md @@ -14,9 +14,11 @@ exactly goes to the default `ui_automation` transport before anything is sent. GFLOW_CLI_TRANSPORT=direct_http gflow image t2i "a paper boat on a pond" ``` -The setting applies to `gflow image t2i` / `i2i` / `generate` and to the MCP image tool, -in-process and as a queued job. Batch runs (`gflow run`, `gflow image batch`) still use the -UI transport. +The setting applies to `gflow image t2i` / `i2i` / `generate`, to the MCP image tool +(in-process and as a queued job), and to each row of `gflow run` (from the environment, or +`"transport": "direct_http"` in the config; a `"ref": "batch:N"` row is served too). +`gflow image batch` resolves to the same transport, but its rows run the inherited UI batch +method, which flow.google.com refuses on every transport. ## What it serves @@ -29,10 +31,10 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Aspect 9:16, 16:9 | yes | live generations (768x1376, 1376x768) | | Aspect 1:1, 4:3, 3:4 | yes | captures of Flow's own submit | | Count 1 to 4 | yes | live generations: 2, 3 and 4 entries in one request returned 2, 3 and 4 images | -| One `--ref` to an image already in the project (with its display name), one image | yes | a live generation | -| One `--ref ./photo.png` (a local file) | yes, after the upload | the upload runs on the UI transport, then the generation goes direct; a live generation | +| One ref made in this run: a `gflow run` row's `"ref": "batch:N"`, one image | yes | a live `gflow run` | +| One `--ref ./photo.png` (a local file not yet in the catalog), one image | yes, after the upload | the upload runs on the UI transport, then the generation goes direct; a live generation | | One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | -| One `@Name` mention of a character in the project | yes, when exactly one character has that name | the id is read from the project; a live generation | +| One `@Name` mention of a character in the project | yes, when exactly one character has that name (trimmed, case-insensitive, as the UI picker matches) | the id is read from the project; a live generation | | Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | | Several refs, several characters, a ref plus a character, or a ref or character with count 2-4 | no | not captured | | A mention whose name matches no character, or several | no | the UI picker decides | @@ -49,7 +51,7 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Flow answers a redirect, HTTP 401 or HTTP 403 | no: it was sent once and refused | the request is submitted a second time, through `ui_automation`'s own page | | A timeout, a dropped connection or any other HTTP status | no | the run stops with a network error (`next_action: reconcile`); gflow does **not** resend, because Flow may have made the image | | Flow refuses the prompt | no | the same refusal error as the UI path | -| A referenced image was deleted in Flow | no | **not measured**: the UI path re-uploads the local copy (#772); the direct path reports the error and does not | +| A `--ref` found in the local catalog (a media id, or a file used before) | no | the catalog may be stale; the UI path proves the image still exists before it submits and refuses at $0 | A sent request is never retried. Every rejected reply drops the cached session token, so a stale one cannot stick in a long-running MCP server or worker. A reCAPTCHA mint is retried @@ -65,10 +67,12 @@ nothing. The page is parked after every direct run, as after a UI run. ## Refusals observed -On 2026-11-23 one direct run on the test profile ended in a WAF refusal (exit 10, -`WafRejectionError`) after about 25 direct generations that day; the same request two -minutes later went through. Which request drew it was not isolated. Flow refused it before -generating, so nothing was billed, and gflow did not resend it. +On 2026-11-23 the test profile made about 90 image generations in one day. Late in that day +Flow answered some requests with a WAF refusal (exit 10, `WafRejectionError`), on direct and +plain requests alike, including a plain text-to-image with no reference; the identical +request usually went through minutes later. The refusals followed the day's volume, not a +request shape: Flow's own submit for each refused shape was captured and matches what the +direct path sends. A refused request was not billed, and gflow did not resend it. ## Speed diff --git a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md index 5303a5fc9..9e229a134 100644 --- a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -416,7 +416,7 @@ No new runtime deps — `httpx` and `sqlite3` (stdlib) are already present. | Live e2e | `tests/e2e/test_direct_image_e2e.py` (t2i, 16:9 x2, model routing, in-project I2I, character) and `test_direct_image_worker_e2e.py` (queued MCP path) pass on a `flow.google.com` profile | A bare `@Name` mention is served: the id is read from the project's own reply. -Count 1-4 is served (N entries returned N images live). Not served directly yet: several refs or characters, local-file refs (Phase 4), batch runs (`image_batch` -calls the UI transport's batch method). The weekly telemetry field (T3.1) is not in this change: it went out for every +Count 1-4 is served (N entries returned N images live). `gflow run` rows go direct, `"ref": "batch:N"` included (measured live). A `--ref` found in the catalog stays on the UI path, which proves it still exists. Not served directly yet: several refs or characters, `gflow image batch` (its batch method is refused on flow.google.com on +every transport). The weekly telemetry field (T3.1) is not in this change: it went out for every image user and needed a notice-version bump that stops EU/EEA uploads until re-consent, so it ships together with the endpoint change. T3.3 (per-image metadata) is in. diff --git a/scripts/dev/spike_direct_image_gate0.py b/scripts/dev/spike_direct_image_gate0.py index 38e1f0e05..640933a31 100644 --- a/scripts/dev/spike_direct_image_gate0.py +++ b/scripts/dev/spike_direct_image_gate0.py @@ -273,6 +273,7 @@ async def main() -> None: ap.add_argument("--direct-aspect", type=int, default=2, help="Phase 2: entry[4] value") ap.add_argument("--capture-aspects", default="", help="Phase 2: Aspect names, comma-separated") ap.add_argument("--capture-ref", action="store_true", help="Phase 2: capture an in-project I2I (spends 2 images of daily quota: a source image, and the referenced submit reaches Flow)") + ap.add_argument("--capture-entity", default="", help="ID:NAME; capture an attached character (spends 1 image)") ap.add_argument("--capture-mention", default="", help="Phase 2: capture an @Name mention (spends 1 image: the referenced submit reaches Flow)") args = ap.parse_args() _FRAME.update(entries=args.direct_entries, aspect=args.direct_aspect) @@ -328,7 +329,14 @@ async def main() -> None: await ui_once("ui", i, client, pid) # G0.3 / G0.4 — $0 captures through the real UI transport. - if args.capture_mention: # Phase 2 T2.2: Flow's own character-mention submit + if args.capture_entity: # Flow's own frame for an attached character + plain prompt + eid, name = args.capture_entity.split(":", 1) + req = GenerateImageRequest( + prompt=_PROMPT, reference_entities=(eid,), reference_entity_names=(name,) + ) + await capture("entity", client, pid, request=req) + await capture("reset_default", client, pid) + elif args.capture_mention: # Phase 2 T2.2: Flow's own character-mention submit from gflow_cli.services.mentions import resolve_and_apply req = await resolve_and_apply( diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 26cde1edd..2ee11fa25 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -46,6 +46,7 @@ _MINT_BUDGET_S = 10.0 # how long a freshly navigated page gets to load reCAPTCHA _MINT_RETRY_S = 0.5 _NAVIGATE_MS = 45_000 # the composer's own budget for reaching a project +_CHARACTER_READ_S = 15.0 # a bare @Name's project read; past it, the UI picker decides _RECONCILE_HINT = ( "Flow may have accepted this image request before the error, so gflow did not resend " "it. Check the project in Flow for the new image before running the command again." @@ -73,13 +74,24 @@ def direct_can_serve(request: GenerateImageRequest) -> bool: def _references_measured(request: GenerateImageRequest) -> bool: """No refs, or the one measured I2I shape: a single in-project image with a display - name (the chip needs it), one output image. A local file is uploaded first (on the UI - transport) and arrives here as such a ref. local_path is not a signal: the CLI fills it - for every catalogued image, generated ones too.""" + name (the chip needs it), one output image, made or uploaded in this run. + + Only a ref this run made (a ``batch:N`` row's image) or uploaded carries no + ``local_path``; one found in the local catalog always does (the CLI's lookup and the + #772 reuse fill it). The catalog can be stale: Flow may have deleted or renamed the + image. The UI path proves the ref still exists before it submits and refuses at $0; a + direct POST cannot, and what Flow does with a dead id is unmeasured. So catalogued + refs stay on the UI path.""" if not request.refs: return True (ref, *more) = request.refs - return not more and ref.in_project and bool(ref.display_name) and request.count == 1 + return ( + not more + and ref.in_project + and bool(ref.display_name) + and not ref.local_path + and request.count == 1 + ) def _characters_measured(request: GenerateImageRequest) -> bool: @@ -101,26 +113,35 @@ def _characters_measured(request: GenerateImageRequest) -> bool: async def _resolve_character( page: Page, project_id: str, request: GenerateImageRequest ) -> tuple[tuple[str, str], ...]: - """Read path: the ``(entity_id, name)`` pair the frame carries. - - A request with the id already has it. A bare mention carries only the name: the id is - read from Flow's own project reply (``read_project``, which also lands the page on the - project for the mint). Anything but exactly one character with that exact name falls - back before any POST, as the UI picker would refuse it. + """Read path: the ``(entity_id, name)`` pair the frame carries, as the project holds it. + + Both forms are checked against Flow's own project reply (``read_project``, which also + lands the page on the project for the mint), as the UI does when it attaches one: + - an id (``--reference-entity``) must be one the project holds; the chip uses Flow's + name for it. A stale or foreign id falls back before any POST. + - a bare mention carries only the name: exactly one character must match it by the + picker's rule (trimmed, case-insensitive), or the UI picker decides. + The project read also measured the difference live: with it the request was accepted, + without it Flow refused an id-carrying request twice (exit 10, 2026-11-23). """ names = request.reference_entity_names if not names: return () - if request.reference_entities: - return ((request.reference_entities[0], names[0]),) try: - project = await read_project(page, project_id) + # Bounded: a slow read must fall back, not hold the generate lock for minutes. + project = await read_project(page, project_id, timeout_s=_CHARACTER_READ_S) except Exception as exc: raise _DirectFallbackError(f"character_read:{type(exc).__name__}") from exc - matches = [c.entity_id for c in project.characters if c.display_name == names[0]] + if request.reference_entities: + wanted_id = request.reference_entities[0] + matches = [c for c in project.characters if c.entity_id == wanted_id] + else: # the picker's own rule (_mc_mention.py): trimmed, case-insensitive, unique + wanted = names[0].strip().casefold() + matches = [c for c in project.characters if c.display_name.strip().casefold() == wanted] if len(matches) != 1: raise _DirectFallbackError(f"character_matches:{len(matches)}") - return ((matches[0], names[0]),) + log.info("direct.character_resolved", source="project_read") + return ((matches[0].entity_id, matches[0].display_name),) class _DirectFallbackError(Exception): diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index f58926f68..60bdc8f1a 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -821,6 +821,10 @@ def handler(request: httpx.Request) -> httpx.Response: return httpx.Response(200, text=_valid_ogiz0b_text()) transport._http_transport = httpx.MockTransport(handler) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.read_project", + AsyncMock(return_value=_project_with("Mate", "Skipper")), + ) req = GenerateImageRequest(prompt="x", **_SKIPPER) # type: ignore[arg-type] await transport.generate_images(project_id="proj-123", request=req) assert builder.call_args.kwargs["characters"] == (("entity-1", "Skipper"),) @@ -860,11 +864,11 @@ def test_agentic_ui_mode_is_not_served() -> None: assert direct_can_serve(GenerateImageRequest(prompt="x", ui_mode=UiMode.AGENTIC)) is False -def test_a_catalogued_reference_with_a_local_copy_is_still_served() -> None: - """The CLI fills local_path for EVERY catalogued image, generated ones too: refusing a - ref with a local copy sent every in-project i2i to the UI (live e2e, 2026-11-23).""" +def test_a_catalogued_reference_keeps_the_ui_path() -> None: + """A catalogued ref (it carries local_path) may be stale: the UI proves it still exists + before submit and refuses at $0; a direct POST cannot (fresh review, 2026-11-23).""" ref = replace(_IN_PROJECT, local_path="face.png", local_sha256="0" * 64) - assert direct_can_serve(GenerateImageRequest(prompt="x", refs=(ref,))) is True + assert direct_can_serve(GenerateImageRequest(prompt="x", refs=(ref,))) is False @pytest.mark.asyncio @@ -1086,3 +1090,93 @@ def handler(request: httpx.Request) -> httpx.Response: await transport.generate_images(project_id="proj-123", request=req) assert ui == [True] assert posts == [] + + +@pytest.mark.asyncio +async def test_a_mention_matches_the_picker_rule_trimmed_and_case_insensitive( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fresh review: @kael must find "Kael " as the UI picker does (_mc_mention.py).""" + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + builder = MagicMock(return_value="f.req=mock_body&at=at-x&") + monkeypatch.setattr("gflow_cli.api.transports.direct_http.build_ogiz0b_body", builder) + read = AsyncMock(return_value=_project_with("Mate", "Kael ")) + monkeypatch.setattr("gflow_cli.api.transports.direct_http.read_project", read) + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + req = GenerateImageRequest(prompt="kael on a pier", reference_entity_names=("kael",)) + await transport.generate_images(project_id="proj-123", request=req) + assert builder.call_args.kwargs["characters"] == (("entity-1", "Kael "),) + assert read.await_args.kwargs["timeout_s"] == 15.0 + + +@pytest.mark.asyncio +async def test_names_differing_only_in_case_are_ambiguous( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fresh review: "Kael" and "KAEL" are one name to the picker, which refuses; so do we.""" + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.read_project", + AsyncMock(return_value=_project_with("Kael", "KAEL")), + ) + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + ui = _watch_ui(transport) + req = GenerateImageRequest(prompt="Kael on a pier", reference_entity_names=("Kael",)) + await transport.generate_images(project_id="proj-123", request=req) + assert ui == [True] + + +@pytest.mark.asyncio +async def test_an_entity_id_the_project_does_not_hold_falls_back_before_any_post( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + """--reference-entity is verified against the project, as the UI attach does: a stale + or foreign id must not reach Flow on the direct path.""" + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.read_project", + AsyncMock(return_value=_project_with("Mate")), # entity-0 only; entity-1 is gone + ) + posts: list[bool] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "POST": + posts.append(True) + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + + transport._http_transport = httpx.MockTransport(handler) + ui = _watch_ui(transport) + req = GenerateImageRequest(prompt="x", **_SKIPPER) # type: ignore[arg-type] + await transport.generate_images(project_id="proj-123", request=req) + assert ui == [True] + assert posts == [] + + +@pytest.mark.asyncio +async def test_an_entity_id_uses_the_name_flow_holds_for_it( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + """The chip carries the character's name as Flow knows it, not a caller's spelling.""" + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + builder = MagicMock(return_value="f.req=mock_body&at=at-x&") + monkeypatch.setattr("gflow_cli.api.transports.direct_http.build_ogiz0b_body", builder) + monkeypatch.setattr( + "gflow_cli.api.transports.direct_http.read_project", + AsyncMock(return_value=_project_with("Mate", "Skipper")), + ) + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + req = GenerateImageRequest( + prompt="x", reference_entities=("entity-1",), reference_entity_names=("skipper",) + ) + await transport.generate_images(project_id="proj-123", request=req) + assert builder.call_args.kwargs["characters"] == (("entity-1", "Skipper"),) diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index 86a61402d..8970bae8c 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -93,10 +93,10 @@ def test_a_model_with_no_measured_wire_name_routes_to_the_ui_transport( assert _image_transports(e2e_env) == [None] -def test_an_in_project_reference_is_generated_by_the_direct_transport( +def test_a_catalogued_reference_routes_to_the_ui_transport( e2e_env: RedactedEnv, tmp_path: Path ) -> None: - """T2.1: an i2i whose --ref is an image this project already holds goes direct.""" + """A --ref found in the catalog may be stale; the UI proves it exists before submit.""" first = _t2i(e2e_env, tmp_path / "source.jpg") assert first.returncode == 0, f"gflow image t2i failed (exit {first.returncode})" with sqlite3.connect(e2e_env["GFLOW_CLI_DB_PATH"]) as db: @@ -125,7 +125,7 @@ def test_an_in_project_reference_is_generated_by_the_direct_transport( ) assert proc.returncode == 0, f"gflow image i2i failed (exit {proc.returncode})" _saved(tmp_path / "night.jpg") - assert _image_transports(e2e_env) == ["direct_http", "direct_http"] + assert _image_transports(e2e_env) == ["direct_http", None] @pytest.mark.skipif( @@ -180,11 +180,15 @@ def test_a_named_character_is_generated_by_the_direct_transport( def test_a_local_file_reference_is_uploaded_then_generated_directly( e2e_env: RedactedEnv, tmp_path: Path ) -> None: - """--ref ./file: the upload runs on the UI transport, then the generation goes direct.""" - first = _t2i(e2e_env, tmp_path / "local.jpg") + """--ref ./fresh.png: uploaded (on the UI transport), then generated directly.""" + from PIL import Image + + first = _t2i(e2e_env, tmp_path / "seed.jpg") # only to obtain a project assert first.returncode == 0, f"gflow image t2i failed (exit {first.returncode})" with sqlite3.connect(e2e_env["GFLOW_CLI_DB_PATH"]) as db: (project_id,) = db.execute("SELECT flow_project_id FROM assets").fetchone() + fresh = tmp_path / "fresh.png" # drawn here, so no catalog knows it + Image.new("RGB", (512, 512), (40, 110, 180)).save(fresh) proc = subprocess.run( [ sys.executable, @@ -192,13 +196,13 @@ def test_a_local_file_reference_is_uploaded_then_generated_directly( "gflow_cli", "image", "i2i", - "the same scene in winter", + "a sailing boat on this blue sea", "--ref", - str(_saved(tmp_path / "local.jpg")), + str(fresh), "--project", project_id, "--out-file", - str(tmp_path / "winter.jpg"), + str(tmp_path / "boat.jpg"), ], capture_output=True, text=True, @@ -206,7 +210,7 @@ def test_a_local_file_reference_is_uploaded_then_generated_directly( env=e2e_env | {"GFLOW_CLI_TRANSPORT": "direct_http"}, ) assert proc.returncode == 0, f"gflow image i2i failed (exit {proc.returncode})" - _saved(tmp_path / "winter.jpg") + _saved(tmp_path / "boat.jpg") assert _image_transports(e2e_env)[-1] == "direct_http" @@ -265,3 +269,40 @@ def test_a_bare_mention_is_generated_by_the_direct_transport( assert proc.returncode == 0, f"gflow image t2i failed (exit {proc.returncode})" _saved(tmp_path / "pier.jpg") assert _image_transports(e2e_env)[-1] == "direct_http" + + +def test_a_run_row_referencing_an_earlier_row_goes_direct( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + """gflow run: "ref": "batch:0" is referenced in place; both rows go direct.""" + config = tmp_path / "run.json" + config.write_text( + json.dumps( + { + "transport": "direct_http", + "prompts": [ + {"text": "a single red apple on a wooden table", "aspect_ratio": "1:1"}, + {"text": "the same apple, now green", "aspect_ratio": "1:1", "ref": "batch:0"}, + ], + } + ), + encoding="utf-8", + ) + proc = subprocess.run( + [ + sys.executable, + "-m", + "gflow_cli", + "run", + "--config", + str(config), + "--output-dir", + str(tmp_path / "run_out"), + ], + capture_output=True, + text=True, + check=False, + env=e2e_env | {"GFLOW_CLI_EXPERIMENTAL_TRANSPORTS": "1"}, + ) + assert proc.returncode == 0, f"gflow run failed (exit {proc.returncode})" + assert _image_transports(e2e_env) == ["direct_http", "direct_http"] From e24787ea5bd1c1cea467cde71d44899fbf536c23 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 07:53:19 +0000 Subject: [PATCH 29/32] feat(telemetry): count runs by image transport in the weekly report (restored) Restores the transports field (direct, ui, other) and notice version 4, on the owner's decision, with the review points applied: - a run is counted only after it produced an image (the empty-reply refusal no longer notes 'ui'); the image's transport is read defensively; - docs say what is counted: one per run, by its last image generation. The telemetry endpoint must accept the transports key before this ships; the CHANGELOG says so. --- CHANGELOG.md | 1 + docs/TELEMETRY.md | 15 ++++----- src/gflow_cli/api/_flow_generation.py | 4 +++ src/gflow_cli/telemetry.py | 44 +++++++++++++++++++-------- tests/api/test_client_image.py | 43 ++++++++++++++++++++++++++ tests/test_telemetry.py | 28 +++++++++++++++++ tests/test_telemetry_notice.py | 14 +++++++++ website/docs/TELEMETRY.md | 15 ++++----- 8 files changed, 137 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11c22d68c..e15733a03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **The weekly usage report counts runs by the image transport that made their images.** A new field, `transports` (`direct`, `ui`, `other`), counts each run that generated an image once, by its last generation. The privacy notice moves to version 4 and names the image transport; in the EU and EEA, consent given to an earlier notice version no longer counts, and uploads stop until `gflow telemetry on` is run again. The telemetry endpoint must accept the `transports` key before this version is released: an endpoint that does not answers 400, and that week's report is dropped. - **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one ref made in this run (a `gflow run` `"ref": "batch:N"` or a newly uploaded file), or one character (`--reference-entity` with its name, or an `@Name` mention), each with one image; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. ### Fixed diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 83eecc120..b78218b91 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -10,7 +10,7 @@ Counters are kept in `/telemetry.db`, separately from the catalo grouped by ISO week and retained for 53 weeks. gflow counts command and flag names, outcomes, coarse duration buckets, command transitions, crash fingerprints made from exception and code names, and generation details read from the local catalog. It also records the storage service category and MCP -client category, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. +client category, image transport, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. `gflow telemetry show` prints the current week's report as JSON, including its random per-week `report_id`; this is the report sent by the uploader. `gflow data stats` shows your own local usage @@ -35,6 +35,7 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | +| `transports` | Counts of runs that generated at least one image, by the transport that made it: `direct` (the experimental direct HTTP transport) or `ui` (UI automation); any other value counts as `other`. One run counts once, by its last image generation. A run that generated no image adds nothing. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent @@ -82,7 +83,7 @@ read your IP address or locale to make this decision, and never sends the timezo Local counters still work in the EU/EEA and remain on your device unless you consent. To allow weekly uploads, run `gflow telemetry on`; this records your choice locally in `/telemetry.consent`, together with the notice version you agreed to. When the -notice changes (version 3 added the browser engine and the Flow site), uploads stop until you run +notice changes (version 4 added image transport), uploads stop until you run `gflow telemetry on` again. Run `gflow telemetry off` to withdraw consent and stop counting and uploads. Environment kill switches still take precedence. @@ -119,13 +120,13 @@ the sender is `src/gflow_cli/telemetry_upload.py` in this repository. ## Notice -Notice version: 3 +Notice version: 4 ```text gflow sends weekly usage totals to improve it, and we share overall figures publicly and with -sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and -your country as a total. No ID, prompts, paths or account details. Each report is added to -totals and discarded. +sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, +error codes, and your country as a total. No ID, prompts, paths or account details. Each +report is added to totals and discarded. Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0 See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` @@ -133,7 +134,7 @@ See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETR The notice shown in the EU/EEA: ```text -gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. +gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry off) See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` diff --git a/src/gflow_cli/api/_flow_generation.py b/src/gflow_cli/api/_flow_generation.py index 7347b6fe9..686d9a46e 100644 --- a/src/gflow_cli/api/_flow_generation.py +++ b/src/gflow_cli/api/_flow_generation.py @@ -15,6 +15,7 @@ import structlog +from gflow_cli import telemetry from gflow_cli.api import routes from gflow_cli.api._engine import ( mint_evaluate_kwargs, @@ -569,6 +570,9 @@ async def _drive_images_generation( instance=_make_instance(), route=routes.batch_generate_images_url(project_id), ) + # getattr: a caller-owned transport may return image objects without the field. + direct = any(getattr(img, "transport", None) == "direct_http" for img in images) + telemetry.note_transport("direct" if direct else "ui") if on_checkpoint is not None: on_checkpoint( GenerationCheckpoint( diff --git a/src/gflow_cli/telemetry.py b/src/gflow_cli/telemetry.py index b9dce9692..ae4a3fbd4 100644 --- a/src/gflow_cli/telemetry.py +++ b/src/gflow_cli/telemetry.py @@ -53,22 +53,22 @@ def _debug(event: str, **kw: str) -> None: OFF_FILE = "telemetry.off" CONSENT_FILE = "telemetry.consent" SCHEMA = 1 -NOTICE_VERSION = 3 +NOTICE_VERSION = 4 NOTICE_TEXT = ( "gflow sends weekly usage totals to improve it, and we share overall figures publicly and " "with\n" - "sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and\n" - "your country as a total. No ID, prompts, paths or account details. Each report is added to\n" - "totals and discarded.\n" + "sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used,\n" + "error codes, and your country as a total. No ID, prompts, paths or account details. Each\n" + "report is added to totals and discarded.\n" "Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0\n" "See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY" ) NOTICE_TEXT_CONSENT = ( "gflow can send weekly usage totals to help improve it; overall figures are shared publicly " "and " - "with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, " - "and your country as a total. No ID, prompts, paths or account details. Each report is " - "added to totals and discarded.\n" + "with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site " + "used, error codes, and your country as a total. No ID, prompts, paths or account details. " + "Each report is added to totals and discarded.\n" "In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry " "off)\n" "See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY" @@ -450,6 +450,7 @@ def _connect(home: Path) -> sqlite3.Connection: _RUN_FACTS: ContextVar[dict[str, str] | None] = ContextVar("gflow_run_facts", default=None) _ENGINES = frozenset({"playwright", "patchright"}) _HOSTS = {"labs": "labs", "migrated": "flow"} +_TRANSPORTS = frozenset({"direct", "ui"}) def _facts() -> dict[str, str]: @@ -479,14 +480,23 @@ def note_host(kind: str | None) -> None: _facts()["host"] = _HOSTS[kind] +def note_transport(kind: str) -> None: + """Note the image transport used (closed enum: direct, ui; anything else is ``other``).""" + _facts()["transport"] = kind if kind in _TRANSPORTS else "other" + + def _take_run_facts() -> list[tuple[str, str]]: """The noted facts as counter keys, cleared so the next run starts empty.""" facts = _facts() noted = dict(facts) # snapshot, then clear: a concurrent clear cannot raise here facts.clear() # a host noted without a launch must not carry into a later run - if "engine" not in noted: - return [] - return [("engine", noted["engine"]), ("host", noted.get("host", "unknown"))] + out: list[tuple[str, str]] = [] + if "engine" in noted: + out.append(("engine", noted["engine"])) + out.append(("host", noted.get("host", "unknown"))) + if "transport" in noted: + out.append(("transport", noted["transport"])) + return out def flush_run_facts(surface: Literal["cli", "mcp"]) -> None: @@ -933,6 +943,7 @@ def _report_counter_targets() -> dict[str, Any]: "mcp_clients": {}, "engines": {}, "hosts": {}, + "transports": {}, "tools": tools, "nested": {"flag": flags, "exit": exits, "duration": durations, "tool": tools}, } @@ -979,8 +990,15 @@ def _add_scalar_counter( elif kind == "crash": values = targets["crashes"].setdefault(surface, {}) values[key] = values.get(key, 0) + count - elif kind in ("client", "engine", "host"): - values = targets[{"client": "mcp_clients", "engine": "engines", "host": "hosts"}[kind]] + elif kind in ("client", "engine", "host", "transport"): + values = targets[ + { + "client": "mcp_clients", + "engine": "engines", + "host": "hosts", + "transport": "transports", + }[kind] + ] values[key] = values.get(key, 0) + count @@ -1105,5 +1123,5 @@ def build_report(week: str) -> dict[str, object]: "crashes": counters["crashes"], "tools": counters["tools"], # Sent only when non-empty: an endpoint older than #1326 rejects the keys. - **{k: counters[k] for k in ("engines", "hosts") if counters[k]}, + **{k: counters[k] for k in ("engines", "hosts", "transports") if counters[k]}, } diff --git a/tests/api/test_client_image.py b/tests/api/test_client_image.py index 73aa7f053..3bc2b89c0 100644 --- a/tests/api/test_client_image.py +++ b/tests/api/test_client_image.py @@ -24,6 +24,7 @@ import pytest import structlog +from gflow_cli import telemetry from gflow_cli.api.client import FlowApiClient, FlowApiError from gflow_cli.api.dto import GeneratedImage from gflow_cli.api.image import Aspect, GenerateImageRequest @@ -1015,3 +1016,45 @@ async def test_a_redirect_off_an_allowed_host_is_refused_and_nothing_is_written( _make_image(fife_url="https://flow.google.com/asb/opaque=s0"), out ) assert not out.exists() + + +class TestImageGenerationTransportTelemetry: + async def test_notes_direct_transport_when_image_has_direct_http( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + noted: list[str] = [] + monkeypatch.setattr(telemetry, "note_transport", noted.append) + img = dataclasses.replace(_make_image(), transport="direct_http") + transport = _FakeTransport([img]) + client = _client_with_transport(tmp_path, transport) + + await client.generate_image(project_id="proj-1", req=_make_req()) + + assert noted == ["direct"] + + async def test_notes_ui_transport_when_image_has_no_transport( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + noted: list[str] = [] + monkeypatch.setattr(telemetry, "note_transport", noted.append) + img = _make_image() + assert img.transport is None + transport = _FakeTransport([img]) + client = _client_with_transport(tmp_path, transport) + + await client.generate_image(project_id="proj-1", req=_make_req()) + + assert noted == ["ui"] + + async def test_a_run_that_made_no_image_notes_no_transport( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Counted only after the empty-reply refusal: no image, no transport fact.""" + noted: list[str] = [] + monkeypatch.setattr(telemetry, "note_transport", noted.append) + client = _client_with_transport(tmp_path, _FakeTransport([])) + + with pytest.raises(ContentPolicyError): + await client.generate_image(project_id="proj-1", req=_make_req()) + + assert noted == [] diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 18933ee3d..f8e87466d 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -333,6 +333,34 @@ def test_an_engine_outside_the_enum_is_other_and_facts_reset_per_command(tmp_hom assert report["hosts"] == {"labs": 1} +def test_a_transport_run_counts_its_transport_once(tmp_home: Path) -> None: + telemetry.note_transport("direct") + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"direct": 1} + + +def test_a_transport_ui_counts_ui(tmp_home: Path) -> None: + telemetry.note_transport("ui") + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"ui": 1} + + +def test_a_transport_outside_the_enum_is_other(tmp_home: Path) -> None: + telemetry.note_transport("custom-grpc") + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"other": 1} + + +def test_an_unlisted_transport_counts_other(tmp_home: Path) -> None: + telemetry.note_transport("direct_http") # a raw transport name never reaches the totals + telemetry.record("cli", "image t2i", [], "0", 3.0) + report = _report() + assert report["transports"] == {"other": 1} + + def test_the_worker_flushes_a_queued_job_s_facts(tmp_home: Path) -> None: telemetry.note_engine("playwright") telemetry.note_host("migrated") diff --git a/tests/test_telemetry_notice.py b/tests/test_telemetry_notice.py index 20fe304fe..55b0f6789 100644 --- a/tests/test_telemetry_notice.py +++ b/tests/test_telemetry_notice.py @@ -511,3 +511,17 @@ def test_consent_to_an_earlier_notice_is_not_consent( assert telemetry.consent_at() is None # v2 wrote a bare timestamp telemetry.set_consent() assert telemetry.consent_at() is not None + + +def test_consent_to_v3_notice_is_not_consent_for_v4( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A v3 consent must be renewed now that notice v4 names image transport.""" + home = tmp_path / "gflow_home" + home.mkdir(exist_ok=True) + monkeypatch.setenv("GFLOW_CLI_HOME", str(home)) + monkeypatch.setattr(telemetry, "consent_region", lambda: True) + (home / telemetry.CONSENT_FILE).write_text("2026-11-01T00:00:00+00:00\n3", encoding="utf-8") + assert telemetry.consent_at() is None + telemetry.set_consent() + assert telemetry.consent_at() is not None diff --git a/website/docs/TELEMETRY.md b/website/docs/TELEMETRY.md index cf689fe5f..2fa31f163 100644 --- a/website/docs/TELEMETRY.md +++ b/website/docs/TELEMETRY.md @@ -10,7 +10,7 @@ Counters are kept in `/telemetry.db`, separately from the catalo grouped by ISO week and retained for 53 weeks. gflow counts command and flag names, outcomes, coarse duration buckets, command transitions, crash fingerprints made from exception and code names, and generation details read from the local catalog. It also records the storage service category and MCP -client category, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. +client category, image transport, and, for runs that selected a browser engine, the engine and the Flow site that served them. Prompts, argument values and other free-form text are not used as counter keys. `gflow telemetry show` prints the current week's report as JSON, including its random per-week `report_id`; this is the report sent by the uploader. `gflow data stats` shows your own local usage @@ -35,6 +35,7 @@ counts. | `crashes` | Counts of code-only crash fingerprints by surface. A fingerprint contains exception class names, up to three gflow-cli function names, and a third-party package marker where relevant. | | `engines` | Counts of generation, project and catalog commands and queued jobs that selected a browser engine, by engine: `playwright`, `patchright`, or `other`. A run is counted when the engine is selected, so a launch that then fails (a missing patchright install, a locked profile) still counts, which is what sizes an engine-specific failure. `gflow auth` commands and runs that launch no browser are not counted. | | `hosts` | For the same runs, the Flow site that served them, as observed from the page address when a generation is routed: `labs` (labs.google), `flow` (flow.google.com), or `unknown` when the run routed no generation (for example a credits, project or character read, or a run that failed first). It records which site served a run and says nothing about what that site supports. | +| `transports` | Counts of runs that generated at least one image, by the transport that made it: `direct` (the experimental direct HTTP transport) or `ui` (UI automation); any other value counts as `other`. One run counts once, by its last image generation. A run that generated no image adds nothing. | | `tools` | Counts by packaged prompt-tool name and whether it expanded or left the prompt unchanged. Custom tools, including tools that shadow a packaged name, are counted only as `custom`. | ## What is never sent @@ -82,7 +83,7 @@ read your IP address or locale to make this decision, and never sends the timezo Local counters still work in the EU/EEA and remain on your device unless you consent. To allow weekly uploads, run `gflow telemetry on`; this records your choice locally in `/telemetry.consent`, together with the notice version you agreed to. When the -notice changes (version 3 added the browser engine and the Flow site), uploads stop until you run +notice changes (version 4 added image transport), uploads stop until you run `gflow telemetry on` again. Run `gflow telemetry off` to withdraw consent and stop counting and uploads. Environment kill switches still take precedence. @@ -119,13 +120,13 @@ the sender is `src/gflow_cli/telemetry_upload.py` in this repository. ## Notice -Notice version: 3 +Notice version: 4 ```text gflow sends weekly usage totals to improve it, and we share overall figures publicly and with -sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and -your country as a total. No ID, prompts, paths or account details. Each report is added to -totals and discarded. +sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, +error codes, and your country as a total. No ID, prompts, paths or account details. Each +report is added to totals and discarded. Turn it off: gflow telemetry off, or set GFLOW_CLI_TELEMETRY=0 See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` @@ -133,7 +134,7 @@ See exactly what is sent: gflow telemetry show. Full notice: gflow docs TELEMETR The notice shown in the EU/EEA: ```text -gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. +gflow can send weekly usage totals to help improve it; overall figures are shared publicly and with sponsors. Commands, flag names, models, browser engine, image transport, the Flow site used, error codes, and your country as a total. No ID, prompts, paths or account details. Each report is added to totals and discarded. In your region nothing is sent unless you agree: gflow telemetry on (undo: gflow telemetry off) See exactly what would be sent: gflow telemetry show. Full notice: gflow docs TELEMETRY ``` From c26c296ad8615b203e4e401f716a020d7ed0e82f Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 08:06:21 +0000 Subject: [PATCH 30/32] feat(transport): upload local files with one direct maseQ POST (Phase 4) A local --ref is uploaded by one direct maseQ request (frame and its UPLOAD_IMAGE reCAPTCHA action captured from Flow's own upload), then generated directly. Live: a direct upload returned the media id, and a fresh-file i2i uploaded and generated without the composer. An upload that cannot start uses the UI upload; one that fails after the send is not resent. Also from CodeRabbit on #1442: the character read has one outer deadline; docs place the catalogued-ref fallback before the request and separate a refusal reply (not resent) from a 403 (submitted once more via the UI). --- CHANGELOG.md | 2 +- docs/DIRECT_TRANSPORT.md | 9 +- .../PLAN.md | 3 + scripts/dev/spike_direct_image_gate0.py | 104 ++++++++++++++- src/gflow_cli/api/transports/direct_http.py | 124 +++++++++++++++--- src/gflow_cli/api/transports/frame_builder.py | 25 ++++ tests/api/transports/test_direct_http.py | 111 ++++++++++++++++ tests/api/transports/test_frame_builder.py | 38 ++++++ tests/e2e/test_direct_image_e2e.py | 2 +- 9 files changed, 393 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e15733a03..3e3d6b4d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - **The weekly usage report counts runs by the image transport that made their images.** A new field, `transports` (`direct`, `ui`, `other`), counts each run that generated an image once, by its last generation. The privacy notice moves to version 4 and names the image transport; in the EU and EEA, consent given to an earlier notice version no longer counts, and uploads stop until `gflow telemetry on` is run again. The telemetry endpoint must accept the `transports` key before this version is released: an endpoint that does not answers 400, and that week's report is dropped. -- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one ref made in this run (a `gflow run` `"ref": "batch:N"` or a newly uploaded file), or one character (`--reference-entity` with its name, or an `@Name` mention), each with one image; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. +- **An experimental `direct_http` image transport ([docs/DIRECT_TRANSPORT.md](docs/DIRECT_TRANSPORT.md)).** With `GFLOW_CLI_TRANSPORT=direct_http`, an image on `flow.google.com` is generated by one direct request to Flow's `ogiZ0b` RPC; the browser only mints the reCAPTCHA token and holds the session. It serves text-to-image with `nano2`/`nano21`, every aspect, one to four images, one ref made in this run (a `gflow run` `"ref": "batch:N"`, or a local file, which is itself uploaded by one direct `maseQ` request), or one character (`--reference-entity` with its name, or an `@Name` mention), each with one image; any other request runs on the UI transport before anything is sent. A sent request is never resent: a timeout or an unexpected status stops the run with `next_action: reconcile`, and a redirect, HTTP 401 or HTTP 403 (Flow accepted nothing) falls back to the UI transport. Each generated image records `"transport": "direct_http"` in its catalog metadata. ### Fixed diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md index c06e218e5..9a8498b5a 100644 --- a/docs/DIRECT_TRANSPORT.md +++ b/docs/DIRECT_TRANSPORT.md @@ -32,7 +32,7 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Aspect 1:1, 4:3, 3:4 | yes | captures of Flow's own submit | | Count 1 to 4 | yes | live generations: 2, 3 and 4 entries in one request returned 2, 3 and 4 images | | One ref made in this run: a `gflow run` row's `"ref": "batch:N"`, one image | yes | a live `gflow run` | -| One `--ref ./photo.png` (a local file not yet in the catalog), one image | yes, after the upload | the upload runs on the UI transport, then the generation goes direct; a live generation | +| One `--ref ./photo.png` (a local file not yet in the catalog), one image | yes | uploaded by one direct `maseQ` request (reCAPTCHA action `UPLOAD_IMAGE`), then generated directly; a live generation | | One `--reference-entity` with its `--reference-entity-name` | yes | a live generation | | One `@Name` mention of a character in the project | yes, when exactly one character has that name (trimmed, case-insensitive, as the UI picker matches) | the id is read from the project; a live generation | | Any other model (`nano-pro`, `nano2-lite`, `imagen4`) | no | wire name not captured | @@ -51,7 +51,7 @@ Flow's own submit. Everything else is routed to `ui_automation` before any reque | Flow answers a redirect, HTTP 401 or HTTP 403 | no: it was sent once and refused | the request is submitted a second time, through `ui_automation`'s own page | | A timeout, a dropped connection or any other HTTP status | no | the run stops with a network error (`next_action: reconcile`); gflow does **not** resend, because Flow may have made the image | | Flow refuses the prompt | no | the same refusal error as the UI path | -| A `--ref` found in the local catalog (a media id, or a file used before) | no | the catalog may be stale; the UI path proves the image still exists before it submits and refuses at $0 | +| A `--ref` found in the local catalog (a media id, or a file used before) | yes: the selector routes it before any request | the request runs on `ui_automation`; the catalog may be stale, and the UI path proves the image still exists before it submits, refusing at $0 | A sent request is never retried. Every rejected reply drops the cached session token, so a stale one cannot stick in a long-running MCP server or worker. A reCAPTCHA mint is retried @@ -72,7 +72,10 @@ Flow answered some requests with a WAF refusal (exit 10, `WafRejectionError`), o plain requests alike, including a plain text-to-image with no reference; the identical request usually went through minutes later. The refusals followed the day's volume, not a request shape: Flow's own submit for each refused shape was captured and matches what the -direct path sends. A refused request was not billed, and gflow did not resend it. +direct path sends. Those refusals came back as a refusal reply (exit 10): nothing was billed, +and gflow did not resend them. This differs from an HTTP 403, a redirect or a 401 on the +direct POST, where Flow accepted nothing and the request is submitted once more through +`ui_automation` (see the failure table). ## Speed diff --git a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md index 9e229a134..08b78094d 100644 --- a/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -420,3 +420,6 @@ Count 1-4 is served (N entries returned N images live). `gflow run` rows go dire every transport). The weekly telemetry field (T3.1) is not in this change: it went out for every image user and needed a notice-version bump that stops EU/EEA uploads until re-consent, so it ships together with the endpoint change. T3.3 (per-image metadata) is in. +Phase 4 is in: a local file is uploaded by one direct `maseQ` POST (frame and the +`UPLOAD_IMAGE` action captured from Flow's own upload; a direct upload returned the media id +live, and a fresh-file i2i uploaded and generated directly). diff --git a/scripts/dev/spike_direct_image_gate0.py b/scripts/dev/spike_direct_image_gate0.py index 640933a31..f6263cd91 100644 --- a/scripts/dev/spike_direct_image_gate0.py +++ b/scripts/dev/spike_direct_image_gate0.py @@ -261,6 +261,100 @@ def on_request(req: Any) -> None: frames=posts) +async def direct_upload( + *, minter: TokenMinter, project_id: str, tokens: Any, headers: dict[str, str], image: Path +) -> None: + """Phase 4: one direct maseQ upload, built from scratch (frame captured 2026-11-23).""" + import base64 + import mimetypes + + from gflow_cli.api.transports._mc_common import _first_uuid + + t0 = time.perf_counter() + token = await minter.mint("UPLOAD_IMAGE") + mint_ms = _ms(t0) + ctx: list[Any] = [None, 22, None, None, None, project_id, None, None, None, None, [token, 1]] + mime = mimetypes.guess_type(image.name)[0] or "image/png" + name = f"{image.stem}-{secrets.token_hex(4)}{image.suffix}" + payload = [ctx, base64.b64encode(image.read_bytes()).decode("ascii"), mime, 1, + None, None, None, None, name, None, + str(uuid.uuid4()).upper(), str(uuid.uuid4()).upper()] + body = urlencode({ + "f.req": json.dumps([[["maseQ", json.dumps(payload, separators=(",", ":")), None, + "generic"]]]), + "at": tokens.at, + }) + query = {"rpcids": "maseQ", "source-path": f"/project/{project_id}", "bl": tokens.bl, + "f.sid": tokens.fsid, "hl": "en", "_reqid": str(1000 + secrets.randbelow(9000)), + "rt": "c"} + url = f"{_BATCHEXECUTE}?{urlencode({k: v for k, v in query.items() if v})}" + post_headers = { + **headers, + "content-type": "application/x-www-form-urlencoded;charset=UTF-8", + "x-same-domain": "1", "origin": _ORIGIN, "referer": f"{_ORIGIN}/project/{project_id}", + "sec-fetch-site": "same-origin", "sec-fetch-mode": "cors", "sec-fetch-dest": "empty", + } + t1 = time.perf_counter() + async with httpx.AsyncClient(follow_redirects=False, trust_env=False, + timeout=httpx.Timeout(60.0, connect=10.0)) as hx: + resp = await hx.post(url, content=body, headers=post_headers) + errors = rpc_errors(resp.text) if resp.status_code == 200 else [] + media_id = _first_uuid(resp.text) if resp.status_code == 200 else None + _log("direct_upload", status=resp.status_code, media_id=media_id, display_name=name, + errors=[{"code": e.code, "reasons": list(e.reasons)} for e in errors], + head=None if resp.status_code == 200 else resp.text[:200], + mint_ms=mint_ms, post_ms=_ms(t1), body_len=len(body)) + + +async def capture_upload(client: Any, project_id: str, image: Path) -> None: + """Phase 4: Flow's own maseQ upload frame, route-aborted ($0: no asset is created).""" + page = client._page # noqa: SLF001 - spike-only + seen: list[dict[str, Any]] = [] + + async def on_route(route: Any) -> None: + req = route.request + data = (req.post_data_buffer or b"").decode("utf-8", errors="replace") + if "maseQ" in req.url or "maseQ" in data: + seen.append({"url": req.url.split("?", 1)[0], "query": parse_qs(req.url.split("?", 1)[-1]), + "headers": sorted(req.headers), "data": data}) + await route.abort() + else: + await route.continue_() + + from gflow_cli.api._engine import mint_evaluate_kwargs + + # Record the reCAPTCHA action the page mints for the upload (main world, like the minter). + hook = """() => { + const ent = window.grecaptcha && window.grecaptcha.enterprise; + if (!ent || ent.__gflowHooked) return !!ent; + const orig = ent.execute.bind(ent); + window.__gflowActions = []; + ent.execute = (key, opts) => { window.__gflowActions.push(opts && opts.action); return orig(key, opts); }; + ent.__gflowHooked = true; + return true; + }""" + hooked = await page.evaluate(hook, **mint_evaluate_kwargs()) + await page.route("**/data/batchexecute**", on_route) + try: + with contextlib.suppress(Exception): + await asyncio.wait_for(client.transport.upload_reference(project_id=project_id, + path=image), timeout=60) + finally: + await page.unroute("**/data/batchexecute**", on_route) + frames = [] + for b in seen: + freq = json.loads(parse_qs(b["data"]).get("f.req", ["null"])[0] or "null") + for call in (freq or [[]])[0]: + if call and call[0] == "maseQ": + frames.append(_redact(json.loads(call[1]))) + actions = await page.evaluate("() => window.__gflowActions || null", **mint_evaluate_kwargs()) + _log("upload_actions", hooked=hooked, actions=actions) + _log("upload_capture", posts=len(seen), rpcids=[b["query"].get("rpcids") for b in seen], + source_path=[b["query"].get("source-path") for b in seen], + headers=seen[0]["headers"] if seen else [], frames=frames, + body_len=[len(b["data"]) for b in seen]) + + async def main() -> None: ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--profile", default="denon82") @@ -273,6 +367,8 @@ async def main() -> None: ap.add_argument("--direct-aspect", type=int, default=2, help="Phase 2: entry[4] value") ap.add_argument("--capture-aspects", default="", help="Phase 2: Aspect names, comma-separated") ap.add_argument("--capture-ref", action="store_true", help="Phase 2: capture an in-project I2I (spends 2 images of daily quota: a source image, and the referenced submit reaches Flow)") + ap.add_argument("--direct-upload", default="", help="Phase 4: FILE; one direct maseQ upload (creates an asset, $0)") + ap.add_argument("--capture-upload", default="", help="Phase 4: FILE; capture its maseQ upload ($0)") ap.add_argument("--capture-entity", default="", help="ID:NAME; capture an attached character (spends 1 image)") ap.add_argument("--capture-mention", default="", help="Phase 2: capture an @Name mention (spends 1 image: the referenced submit reaches Flow)") args = ap.parse_args() @@ -315,6 +411,10 @@ async def main() -> None: await discover_site_key(page) minter = TokenMinter(page) + if args.direct_upload: # Phase 4: one direct maseQ upload + await direct_upload(minter=minter, project_id=pid, tokens=tokens, + headers=headers, image=Path(args.direct_upload)) + return if args.captures_only: args.n = args.ui_n = 0 # G0.1 — N consecutive direct POSTs, UI control on the first refusal. @@ -329,7 +429,9 @@ async def main() -> None: await ui_once("ui", i, client, pid) # G0.3 / G0.4 — $0 captures through the real UI transport. - if args.capture_entity: # Flow's own frame for an attached character + plain prompt + if args.capture_upload: # Phase 4: the maseQ upload frame ($0) + await capture_upload(client, pid, Path(args.capture_upload)) + elif args.capture_entity: # Flow's own frame for an attached character + plain prompt eid, name = args.capture_entity.split(":", 1) req = GenerateImageRequest( prompt=_PROMPT, reference_entities=(eid,), reference_entity_names=(name,) diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 2ee11fa25..61aadbf9d 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -3,12 +3,14 @@ from __future__ import annotations import asyncio +import mimetypes import secrets import time import uuid from collections.abc import Callable from dataclasses import replace from http.cookiejar import CookieJar, DefaultCookiePolicy +from pathlib import Path from typing import TYPE_CHECKING import httpx @@ -16,20 +18,19 @@ from gflow_cli.api import flow_wire from gflow_cli.api._engine import mint_evaluate_kwargs -from gflow_cli.api.image import Model +from gflow_cli.api.image import ImageRef, Model from gflow_cli.api.recaptcha import TokenMinter from gflow_cli.api.transports._common import flow_host_kind +from gflow_cli.api.transports._mc_common import _first_uuid # pyright: ignore[reportPrivateUsage] from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images -from gflow_cli.api.transports.frame_builder import build_ogiz0b_body +from gflow_cli.api.transports.frame_builder import build_maseq_body, build_ogiz0b_body from gflow_cli.api.transports.migrated_character import read_project from gflow_cli.api.transports.ui_automation import UiAutomationTransport from gflow_cli.auth.cookies import sent_to_flow_host from gflow_cli.config import UiMode, get_settings, resolve_ui_mode -from gflow_cli.errors import NetworkError, RecaptchaError +from gflow_cli.errors import NetworkError, RecaptchaError, WireFormatError if TYPE_CHECKING: - from pathlib import Path - from playwright.async_api import Page from gflow_cli.api.dto import GeneratedImage @@ -51,6 +52,13 @@ "Flow may have accepted this image request before the error, so gflow did not resend " "it. Check the project in Flow for the new image before running the command again." ) +_UPLOAD_RECONCILE_HINT = ( + "Flow may have stored this upload before the error, so gflow did not resend it. Check " + "the project in Flow for the uploaded image before running the command again." +) +_SUBMIT = ("ogiZ0b", "IMAGE_GENERATION", "image submit", _RECONCILE_HINT) +_UPLOAD = ("maseQ", "UPLOAD_IMAGE", "image upload", _UPLOAD_RECONCILE_HINT) +_RpcSpec = tuple[str, str, str, str] # rpcid, reCAPTCHA action, noun, reconcile hint def direct_can_serve(request: GenerateImageRequest) -> bool: @@ -129,7 +137,10 @@ async def _resolve_character( return () try: # Bounded: a slow read must fall back, not hold the generate lock for minutes. - project = await read_project(page, project_id, timeout_s=_CHARACTER_READ_S) + # One outer deadline: read_project's own budget is per attempt, and it retries. + project = await asyncio.wait_for( + read_project(page, project_id, timeout_s=_CHARACTER_READ_S), _CHARACTER_READ_S + ) except Exception as exc: raise _DirectFallbackError(f"character_read:{type(exc).__name__}") from exc if request.reference_entities: @@ -152,14 +163,14 @@ def __init__(self, reason: str) -> None: self.reason = reason -def _reconcile_error(detail: str, *, status: int | None = None) -> NetworkError: +def _reconcile_error(detail: str, spec: _RpcSpec, *, status: int | None = None) -> NetworkError: """A failure after the POST was sent: never resent, the caller reconciles.""" return NetworkError( detail=f"{detail}; not resent", status=status, - route="batchexecute:ogiZ0b", + route=f"batchexecute:{spec[0]}", next_action="reconcile", - remediation_hint=_RECONCILE_HINT, + remediation_hint=spec[3], ) @@ -204,8 +215,8 @@ async def _shell( raise _DirectFallbackError(f"shell_tokens:{type(exc).__name__}") from exc -async def _mint(page: Page, project_id: str) -> str: - """The single browser step: an IMAGE_GENERATION token minted on the project page. +async def _mint(page: Page, project_id: str, action: str) -> str: + """The single browser step: a reCAPTCHA token for ``action``, minted on the project page. The page must end up on flow.google.com: an account Flow serves on labs.google is redirected there, and the direct path does not serve it. Right after a navigation the @@ -226,7 +237,7 @@ async def _mint(page: Page, project_id: str) -> str: while True: try: remaining = max(deadline - time.monotonic(), 0.1) - return await asyncio.wait_for(minter.mint("IMAGE_GENERATION"), remaining) + return await asyncio.wait_for(minter.mint(action), remaining) except RecaptchaError as exc: if time.monotonic() >= deadline: raise _DirectFallbackError("mint_failure:RecaptchaError") from exc @@ -236,10 +247,10 @@ async def _mint(page: Page, project_id: str) -> str: def _post_request( - project_id: str, tokens: flow_wire.Tokens, headers: dict[str, str], body: str + rpcid: str, project_id: str, tokens: flow_wire.Tokens, headers: dict[str, str], body: str ) -> httpx.Request: query = { - "rpcids": "ogiZ0b", + "rpcids": rpcid, "source-path": f"/project/{project_id}", "bl": tokens.bl, "f.sid": tokens.fsid, @@ -266,7 +277,7 @@ def _post_request( async def _send_once( - client: httpx.AsyncClient, request: httpx.Request, profile_dir: Path + client: httpx.AsyncClient, request: httpx.Request, profile_dir: Path, spec: _RpcSpec ) -> httpx.Response: """Write path: exactly one send. @@ -281,14 +292,14 @@ async def _send_once( raise _DirectFallbackError(f"connect:{type(exc).__name__}") from exc except (httpx.TimeoutException, httpx.TransportError) as exc: cause = (str(exc).strip().splitlines() or [""])[0][:160] - raise _reconcile_error(f"{type(exc).__name__} on an image submit ({cause})") from exc + raise _reconcile_error(f"{type(exc).__name__} on an {spec[2]} ({cause})", spec) from exc status = response.status_code if status == 200: return response flow_wire.forget_tokens(profile_dir) if 300 <= status < 400 or status in (401, 403): raise _DirectFallbackError(f"http_{status}") - raise _reconcile_error(f"HTTP {status} on an image submit", status=status) + raise _reconcile_error(f"HTTP {status} on an {spec[2]}", spec, status=status) def _client(http_transport: httpx.AsyncBaseTransport | None) -> httpx.AsyncClient: @@ -316,7 +327,7 @@ async def run_direct_images( tokens = await _shell(client, profile_dir, headers) characters = await _resolve_character(page, project_id, request) mint_started = time.perf_counter() - token = await _mint(page, project_id) + token = await _mint(page, project_id, _SUBMIT[1]) mint_ms = int((time.perf_counter() - mint_started) * 1000) body = build_ogiz0b_body( prompt=request.prompt, @@ -338,7 +349,7 @@ async def run_direct_images( ) post_started = time.perf_counter() response = await _send_once( - client, _post_request(project_id, tokens, headers, body), profile_dir + client, _post_request("ogiZ0b", project_id, tokens, headers, body), profile_dir, _SUBMIT ) log.info( "direct.image_post", @@ -351,6 +362,46 @@ async def run_direct_images( return [replace(img, transport="direct_http") for img in images] +async def run_direct_upload( + *, + page: Page, + profile_dir: Path, + project_id: str, + path: Path, + http_transport: httpx.AsyncBaseTransport | None = None, +) -> ImageRef: + """One direct ``maseQ`` upload: read the session, mint ``UPLOAD_IMAGE``, send once. + + The caller has validated the file (size, image header). The display name gets a run- + unique suffix, as the UI's own upload does, so a later chip names this image only. + """ + started = time.perf_counter() + headers = await _session_headers(page, profile_dir) + async with _client(http_transport) as client: + tokens = await _shell(client, profile_dir, headers) + token = await _mint(page, project_id, _UPLOAD[1]) + display_name = f"{path.stem}-{secrets.token_hex(4)}{path.suffix}" + body = build_maseq_body( + project_id=project_id, + recaptcha_token=token, + at_token=tokens.at, + image_bytes=await asyncio.to_thread(path.read_bytes), + mime=mimetypes.guess_type(path.name)[0] or "image/png", + display_name=display_name, + request_ids=(str(uuid.uuid4()).upper(), str(uuid.uuid4()).upper()), + ) + response = await _send_once( + client, _post_request("maseQ", project_id, tokens, headers, body), profile_dir, _UPLOAD + ) + media_id = _first_uuid(response.text) + if media_id is None: + raise WireFormatError( + detail="direct maseQ upload returned no media id", route="batchexecute:maseQ" + ) + log.info("direct.upload", total_ms=int((time.perf_counter() - started) * 1000)) + return ImageRef(name=media_id, display_name=display_name, in_project=True) + + class DirectHttpTransport(UiAutomationTransport): """The UI transport, with measured image requests sent as one direct ``ogiZ0b`` POST.""" @@ -404,6 +455,41 @@ async def generate_images( request, project_id=project_id, name_resolver=name_resolver ) + async def upload_reference(self, *, project_id: str, path: Path) -> ImageRef | None: + """Upload ``path`` with one direct ``maseQ`` POST; the UI upload when nothing was + sent (no session, no token, not flow.google.com, a proxy, a refused session).""" + if not self._setup_done or self._page is None: + msg = "DirectHttpTransport.setup() must be called before upload_reference()" + raise RuntimeError(msg) + page, profile_dir = self._page, self._profile_dir + reason = self._why_not_direct_upload() + if reason is None and profile_dir is not None: + async with self._generate_lock: + await self.park_deferred_page() + try: + return await run_direct_upload( + page=page, + profile_dir=profile_dir, + project_id=project_id, + path=path, + http_transport=self._http_transport, + ) + except _DirectFallbackError as fb: + reason = fb.reason + finally: + await self._park_composer_page(page, event="direct.page_park_failed") + log.info("direct.upload_fallback_to_ui", reason=reason) + return await super().upload_reference(project_id=project_id, path=path) + + def _why_not_direct_upload(self) -> str | None: + if self._profile_dir is None: + return "no_profile_dir" + if get_settings().flow_host == "labs.google": + return "flow_host_labs" + if _proxy_configured(): + return "proxy_configured" + return None + def _why_not_direct(self, request: GenerateImageRequest, project_id: str | None) -> str | None: if not direct_can_serve(request): return "unsupported_shape" diff --git a/src/gflow_cli/api/transports/frame_builder.py b/src/gflow_cli/api/transports/frame_builder.py index 27c19e396..3f3f0b202 100644 --- a/src/gflow_cli/api/transports/frame_builder.py +++ b/src/gflow_cli/api/transports/frame_builder.py @@ -14,6 +14,7 @@ from __future__ import annotations +import base64 import json from urllib.parse import urlencode @@ -74,6 +75,30 @@ def build_ogiz0b_body( return urlencode({"f.req": f_req, "at": at_token}) +def build_maseq_body( + *, + project_id: str, + recaptcha_token: str, + at_token: str, + image_bytes: bytes, + mime: str, + display_name: str, + request_ids: tuple[str, str], +) -> str: + """Return the form-encoded body for one ``maseQ`` (image upload) POST. + + The frame Flow's own upload sends (captured 2026-11-23; a direct POST of it returned the + new media id): the project context with the token, the bytes inline as base64, the MIME + type, ``1``, four nulls, the display name, a null and two client-generated ids. + """ + ctx: list[object] = [None, 22, None, None, None, project_id, None, None, None, None] + ctx.append([recaptcha_token, 1]) + data = base64.b64encode(image_bytes).decode("ascii") + frame = [ctx, data, mime, 1, None, None, None, None, display_name, None, *request_ids] + f_req = json.dumps([[["maseQ", json.dumps(frame, separators=(",", ":")), None, "generic"]]]) + return urlencode({"f.req": f_req, "at": at_token}) + + def _prompt_document( prompt: str, references: tuple[tuple[str, str], ...], diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 60bdc8f1a..25ec27e82 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -16,6 +16,7 @@ from gflow_cli.api.transports._mc_common import UNUSUAL_ACTIVITY_REASON from gflow_cli.api.transports._mc_submit_observe import ogiz0b_reply_images from gflow_cli.api.transports.direct_http import DirectHttpTransport, direct_can_serve +from gflow_cli.api.transports.ui_automation import UiAutomationTransport from gflow_cli.config import get_settings from gflow_cli.errors import NetworkError, WafRejectionError, WireFormatError from tests.api.transports.test_migrated_images import MEDIA, URL, WORKFLOW, image_payload @@ -1180,3 +1181,113 @@ async def test_an_entity_id_uses_the_name_flow_holds_for_it( ) await transport.generate_images(project_id="proj-123", request=req) assert builder.call_args.kwargs["characters"] == (("entity-1", "Skipper"),) + + +# --- Phase 4: direct maseQ upload ---------------------------------------------------------- + +_UPLOADED = "f9efcc22-495d-4c89-9b9b-f9dce015742b" + + +def _maseq_reply(media_id: str = _UPLOADED) -> str: + frame = json.dumps( + [["wrb.fr", "maseQ", json.dumps([[media_id, "proj-123"]]), None, None, None, "generic"]] + ) + return f")]}}'\n{frame}" + + +def _png(tmp_path: Path) -> Path: + f = tmp_path / "face.png" + f.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 32) + return f + + +@pytest.mark.asyncio +async def test_a_local_file_is_uploaded_with_one_direct_maseq_post( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + mint = AsyncMock(return_value="mock_token") + monkeypatch.setattr("gflow_cli.api.recaptcha.TokenMinter.mint", mint) + posts: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, text='"SNlM0e":"at-x","FdrFJe":"sid","cfb2h":"boq_x"' + ) + posts.append(request.url.params["rpcids"]) + return httpx.Response(200, text=_maseq_reply()) + + transport._http_transport = httpx.MockTransport(handler) + ui = AsyncMock() + monkeypatch.setattr(UiAutomationTransport, "upload_reference", ui) + ref = await transport.upload_reference(project_id="proj-123", path=_png(tmp_path)) + assert ref is not None + assert ref.name == _UPLOADED + assert ref.in_project is True + assert ref.display_name.startswith("face-") and ref.display_name.endswith(".png") + assert posts == ["maseQ"] + assert mint.await_args.args[0] == "UPLOAD_IMAGE" + ui.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_an_upload_that_cannot_start_uses_the_ui_upload( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + page = transport._page + assert page is not None + page.context.cookies = AsyncMock(return_value=[]) # no session: nothing can be sent + ui = AsyncMock(return_value=None) + monkeypatch.setattr(UiAutomationTransport, "upload_reference", ui) + await transport.upload_reference(project_id="proj-123", path=_png(tmp_path)) + ui.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_an_upload_failing_after_the_send_is_not_resent( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + transport._http_transport = _shell_and(httpx.Response(500)) + ui = AsyncMock() + monkeypatch.setattr(UiAutomationTransport, "upload_reference", ui) + with pytest.raises(NetworkError) as caught: + await transport.upload_reference(project_id="proj-123", path=_png(tmp_path)) + assert caught.value.next_action == "reconcile" + assert "upload" in (caught.value.remediation_hint or "") + ui.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_an_upload_reply_without_a_media_id_is_a_wire_format_error( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + transport._http_transport = _shell_and(httpx.Response(200, text=")]}'\n[]")) + with pytest.raises(WireFormatError): + await transport.upload_reference(project_id="proj-123", path=_png(tmp_path)) + + +@pytest.mark.asyncio +async def test_the_character_read_has_one_outer_deadline( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + """CodeRabbit: read_project's per-attempt budget plus its retry could stack past 15 s.""" + monkeypatch.setattr("gflow_cli.api.transports.direct_http._CHARACTER_READ_S", 0.2) + + async def slow(*_: Any, **__: Any) -> Any: + await asyncio.sleep(3600) + + monkeypatch.setattr("gflow_cli.api.transports.direct_http.read_project", slow) + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + transport._http_transport = _shell_and(httpx.Response(200, text=_valid_ogiz0b_text())) + ui = _watch_ui(transport) + req = GenerateImageRequest(prompt="x", reference_entity_names=("Skipper",)) + await asyncio.wait_for(transport.generate_images(project_id="proj-123", request=req), timeout=5) + assert ui == [True] diff --git a/tests/api/transports/test_frame_builder.py b/tests/api/transports/test_frame_builder.py index fba3b671b..08eb60454 100644 --- a/tests/api/transports/test_frame_builder.py +++ b/tests/api/transports/test_frame_builder.py @@ -161,3 +161,41 @@ def test_a_character_rides_slot_10_and_a_character_chip() -> None: def test_no_character_leaves_slot_10_empty() -> None: _, inner, _ = _decode_body(_build()) assert inner[1][0][10] is None + + +def test_an_upload_body_matches_flows_own_maseq_frame() -> None: + """Captured 2026-11-23 from Flow's own upload: ctx with the token, inline base64 bytes, + MIME type, 1, four nulls, the display name, null, two client UUIDs.""" + from gflow_cli.api.transports.frame_builder import build_maseq_body + + body = build_maseq_body( + project_id="project-123", + recaptcha_token="captcha-456", + at_token="at-789", + image_bytes=b"\x89PNG\r\n", + mime="image/png", + display_name="face-1a2b3c4d.png", + request_ids=("ID-A", "ID-B"), + ) + form = parse_qs(body) + assert form["at"] == ["at-789"] + rpcid, inner_json, _, generic = json.loads(form["f.req"][0])[0][0] + assert (rpcid, generic) == ("maseQ", "generic") + frame = json.loads(inner_json) + assert frame[0] == [ + None, + 22, + None, + None, + None, + "project-123", + None, + None, + None, + None, + ["captcha-456", 1], + ] + assert frame[1] == "iVBORw0K" # base64 of the bytes + assert frame[2:8] == ["image/png", 1, None, None, None, None] + assert frame[8:] == ["face-1a2b3c4d.png", None, "ID-A", "ID-B"] + assert inner_json == json.dumps(frame, separators=(",", ":")) diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py index 8970bae8c..2edb0006a 100644 --- a/tests/e2e/test_direct_image_e2e.py +++ b/tests/e2e/test_direct_image_e2e.py @@ -180,7 +180,7 @@ def test_a_named_character_is_generated_by_the_direct_transport( def test_a_local_file_reference_is_uploaded_then_generated_directly( e2e_env: RedactedEnv, tmp_path: Path ) -> None: - """--ref ./fresh.png: uploaded (on the UI transport), then generated directly.""" + """--ref ./fresh.png: uploaded by one direct maseQ POST, then generated directly.""" from PIL import Image first = _t2i(e2e_env, tmp_path / "seed.jpg") # only to obtain a project From e7bb3834076c1e330b1f7ae9e14d6d2b609939b3 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 09:55:30 +0000 Subject: [PATCH 31/32] fix(transport): take the upload MIME type from the image bytes CodeRabbit on #1442: the type came from the file name, so a JPEG with no extension was sent as image/png. It now comes from the magic bytes (paths.extension_from_magic), which the caller's validator already checked. Spike: a transport error on the upload POST is recorded as indeterminate, never resent. --- scripts/dev/spike_direct_image_gate0.py | 12 +++++++++--- src/gflow_cli/api/transports/direct_http.py | 16 +++++++++++++--- tests/api/transports/test_direct_http.py | 17 +++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/scripts/dev/spike_direct_image_gate0.py b/scripts/dev/spike_direct_image_gate0.py index f6263cd91..e23932241 100644 --- a/scripts/dev/spike_direct_image_gate0.py +++ b/scripts/dev/spike_direct_image_gate0.py @@ -295,9 +295,15 @@ async def direct_upload( "sec-fetch-site": "same-origin", "sec-fetch-mode": "cors", "sec-fetch-dest": "empty", } t1 = time.perf_counter() - async with httpx.AsyncClient(follow_redirects=False, trust_env=False, - timeout=httpx.Timeout(60.0, connect=10.0)) as hx: - resp = await hx.post(url, content=body, headers=post_headers) + try: + async with httpx.AsyncClient(follow_redirects=False, trust_env=False, + timeout=httpx.Timeout(60.0, connect=10.0)) as hx: + resp = await hx.post(url, content=body, headers=post_headers) + except httpx.HTTPError as exc: + # Flow may have stored the asset before the error: record it, never resend. + _log("direct_upload", status=None, outcome="indeterminate", error=type(exc).__name__, + display_name=name, mint_ms=mint_ms, post_ms=_ms(t1), body_len=len(body)) + return errors = rpc_errors(resp.text) if resp.status_code == 200 else [] media_id = _first_uuid(resp.text) if resp.status_code == 200 else None _log("direct_upload", status=resp.status_code, media_id=media_id, display_name=name, diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 61aadbf9d..0ac847328 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -3,7 +3,6 @@ from __future__ import annotations import asyncio -import mimetypes import secrets import time import uuid @@ -29,6 +28,7 @@ from gflow_cli.auth.cookies import sent_to_flow_host from gflow_cli.config import UiMode, get_settings, resolve_ui_mode from gflow_cli.errors import NetworkError, RecaptchaError, WireFormatError +from gflow_cli.paths import extension_from_magic if TYPE_CHECKING: from playwright.async_api import Page @@ -59,6 +59,15 @@ _SUBMIT = ("ogiZ0b", "IMAGE_GENERATION", "image submit", _RECONCILE_HINT) _UPLOAD = ("maseQ", "UPLOAD_IMAGE", "image upload", _UPLOAD_RECONCILE_HINT) _RpcSpec = tuple[str, str, str, str] # rpcid, reCAPTCHA action, noun, reconcile hint +# The MIME type sent with an upload comes from the bytes, not the file name: a JPEG named +# without an extension must not go out as image/png. The caller's validator already refused +# anything that is not one of these. +_UPLOAD_MIME = { + ".jpg": "image/jpeg", + ".png": "image/png", + ".gif": "image/gif", + ".webp": "image/webp", +} def direct_can_serve(request: GenerateImageRequest) -> bool: @@ -380,13 +389,14 @@ async def run_direct_upload( async with _client(http_transport) as client: tokens = await _shell(client, profile_dir, headers) token = await _mint(page, project_id, _UPLOAD[1]) + image = await asyncio.to_thread(path.read_bytes) display_name = f"{path.stem}-{secrets.token_hex(4)}{path.suffix}" body = build_maseq_body( project_id=project_id, recaptcha_token=token, at_token=tokens.at, - image_bytes=await asyncio.to_thread(path.read_bytes), - mime=mimetypes.guess_type(path.name)[0] or "image/png", + image_bytes=image, + mime=_UPLOAD_MIME[extension_from_magic(image[:12]) or ".png"], display_name=display_name, request_ids=(str(uuid.uuid4()).upper(), str(uuid.uuid4()).upper()), ) diff --git a/tests/api/transports/test_direct_http.py b/tests/api/transports/test_direct_http.py index 25ec27e82..e0912d040 100644 --- a/tests/api/transports/test_direct_http.py +++ b/tests/api/transports/test_direct_http.py @@ -1291,3 +1291,20 @@ async def slow(*_: Any, **__: Any) -> Any: req = GenerateImageRequest(prompt="x", reference_entity_names=("Skipper",)) await asyncio.wait_for(transport.generate_images(project_id="proj-123", request=req), timeout=5) assert ui == [True] + + +@pytest.mark.asyncio +async def test_the_upload_mime_type_comes_from_the_bytes_not_the_name( + transport: DirectHttpTransport, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """CodeRabbit: an extensionless JPEG was sent as image/png (name-based guess).""" + monkeypatch.setattr( + "gflow_cli.api.recaptcha.TokenMinter.mint", AsyncMock(return_value="mock_token") + ) + builder = MagicMock(return_value="f.req=x&at=at-x&") + monkeypatch.setattr("gflow_cli.api.transports.direct_http.build_maseq_body", builder) + transport._http_transport = _shell_and(httpx.Response(200, text=_maseq_reply())) + portrait = tmp_path / "portrait" # no extension + portrait.write_bytes(b"\xff\xd8\xff\xe0" + b"\x00" * 32) + await transport.upload_reference(project_id="proj-123", path=portrait) + assert builder.call_args.kwargs["mime"] == "image/jpeg" From d16c9615161e2909d73d01cc6e0c1fe1c891bb99 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 12:05:12 +0000 Subject: [PATCH 32/32] refactor(transport): return one character pair from the direct read path --- src/gflow_cli/api/transports/direct_http.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py index 0ac847328..210a29970 100644 --- a/src/gflow_cli/api/transports/direct_http.py +++ b/src/gflow_cli/api/transports/direct_http.py @@ -129,7 +129,7 @@ def _characters_measured(request: GenerateImageRequest) -> bool: async def _resolve_character( page: Page, project_id: str, request: GenerateImageRequest -) -> tuple[tuple[str, str], ...]: +) -> tuple[str, str]: """Read path: the ``(entity_id, name)`` pair the frame carries, as the project holds it. Both forms are checked against Flow's own project reply (``read_project``, which also @@ -142,8 +142,6 @@ async def _resolve_character( without it Flow refused an id-carrying request twice (exit 10, 2026-11-23). """ names = request.reference_entity_names - if not names: - return () try: # Bounded: a slow read must fall back, not hold the generate lock for minutes. # One outer deadline: read_project's own budget is per attempt, and it retries. @@ -161,7 +159,7 @@ async def _resolve_character( if len(matches) != 1: raise _DirectFallbackError(f"character_matches:{len(matches)}") log.info("direct.character_resolved", source="project_read") - return ((matches[0].entity_id, matches[0].display_name),) + return (matches[0].entity_id, matches[0].display_name) class _DirectFallbackError(Exception): @@ -334,7 +332,11 @@ async def run_direct_images( headers = await _session_headers(page, profile_dir) async with _client(http_transport) as client: tokens = await _shell(client, profile_dir, headers) - characters = await _resolve_character(page, project_id, request) + characters = ( + (await _resolve_character(page, project_id, request),) + if request.reference_entity_names + else () + ) mint_started = time.perf_counter() token = await _mint(page, project_id, _SUBMIT[1]) mint_ms = int((time.perf_counter() - mint_started) * 1000)