diff --git a/CHANGELOG.md b/CHANGELOG.md index 62aa67656..2dc72add4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### 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 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 - **`gflow video captions` centres the caption box on the text ([#1431](https://github.com/ffroliva/gflow-cli/issues/1431)).** The text was drawn from its layout origin while the box was laid out around its ink, so the box sat above the glyphs and descenders touched or crossed its bottom edge. The text is now drawn so its ink lands where the box expects it, with the same padding above and below. diff --git a/docs/DIRECT_TRANSPORT.md b/docs/DIRECT_TRANSPORT.md new file mode 100644 index 000000000..9a8498b5a --- /dev/null +++ b/docs/DIRECT_TRANSPORT.md @@ -0,0 +1,87 @@ +# 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`, 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 + +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 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 | 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 | +| 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 | + +## 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 (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: 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) | 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 +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`. +- 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. + +## Refusals observed + +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. 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 + +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 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/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..08b78094d --- /dev/null +++ b/docs/superpowers/plans/2026-11-22-direct-http-image-transport/PLAN.md @@ -0,0 +1,425 @@ +# 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-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 + +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 | + +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). `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. +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/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..e23932241 --- /dev/null +++ b/scripts/dev/spike_direct_image_gate0.py @@ -0,0 +1,486 @@ +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 os +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() + 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], + 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: + # 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_() + + 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 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() + 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, + 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") + 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 (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 (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() + _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: + # 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") + ).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.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. + 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_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,) + ) + 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( + 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/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/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: diff --git a/src/gflow_cli/api/flow_wire.py b/src/gflow_cli/api/flow_wire.py index 3127dccef..1f45ab9bf 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,14 @@ async def _shell_tokens( return 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/__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/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/src/gflow_cli/api/transports/direct_http.py b/src/gflow_cli/api/transports/direct_http.py new file mode 100644 index 000000000..210a29970 --- /dev/null +++ b/src/gflow_cli/api/transports/direct_http.py @@ -0,0 +1,516 @@ +"""Direct HTTP transport for image generation on flow.google.com.""" + +from __future__ import annotations + +import asyncio +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 +import structlog + +from gflow_cli.api import flow_wire +from gflow_cli.api._engine import mint_evaluate_kwargs +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_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, WireFormatError +from gflow_cli.paths import extension_from_magic + +if TYPE_CHECKING: + 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__) + +# 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"} + +_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 +_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." +) +_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 +# 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: + """True only for a request whose every wire slot is measured. + + 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 _references_measured(request) + and _characters_measured(request) + 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, 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 not ref.local_path + and request.count == 1 + ) + + +def _characters_measured(request: GenerateImageRequest) -> bool: + """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 + ) + + +async def _resolve_character( + page: Page, project_id: str, request: GenerateImageRequest +) -> 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 + 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 + 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. + 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: + 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)}") + log.info("direct.character_resolved", source="project_read") + return (matches[0].entity_id, matches[0].display_name) + + +class _DirectFallbackError(Exception): + """Internal sentinel: nothing was accepted, so the UI transport may run instead.""" + + def __init__(self, reason: str) -> None: + super().__init__(reason) + self.reason = reason + + +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=f"batchexecute:{spec[0]}", + next_action="reconcile", + remediation_hint=spec[3], + ) + + +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. Read without a URL filter and + matched by domain: a URL filter also drops path-scoped cookies (#222).""" + try: + 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")) + and sent_to_flow_host(c.get("domain", "")) + ) + 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, 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 + 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, wait_until="domcontentloaded", timeout=_NAVIGATE_MS) + except Exception as 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(action), 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( + rpcid: str, project_id: str, tokens: flow_wire.Tokens, headers: dict[str, str], body: str +) -> httpx.Request: + 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", + } + return httpx.Request( + "POST", + f"{_ORIGIN}/_/AiSandboxAngularFrontend/data/batchexecute", + params={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, profile_dir: Path, spec: _RpcSpec +) -> 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, 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 {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 {spec[2]}", spec, 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 + ) + + +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) + 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) + 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=characters, + ) + 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("ogiZ0b", project_id, tokens, headers, body), profile_dir, _SUBMIT + ) + 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] + + +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]) + 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=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()), + ) + 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.""" + + 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 + + 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 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 + ) + + 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" + 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/api/transports/frame_builder.py b/src/gflow_cli/api/transports/frame_builder.py new file mode 100644 index 000000000..3f3f0b202 --- /dev/null +++ b/src/gflow_cli/api/transports/frame_builder.py @@ -0,0 +1,113 @@ +"""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``, ``entry_seeds``) so the output is deterministic under test. + +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, seed, aspect, model, null, copy(ctx), [[[prompt]]], + null, null, null] + inner = [null, [entry, ...], 1, ctx, [batch_id]] # one entry per image, one POST + body = urlencode({"f.req": [[["ogiZ0b", json(inner), null, "generic"]]], "at": at}) +""" + +from __future__ import annotations + +import base64 +import json +from urllib.parse import urlencode + +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( + *, + prompt: str, + model: str, + project_id: str, + recaptcha_token: str, + at_token: str, + batch_id: str, + 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. + + One entry per image: ``len(entry_seeds)`` is the image count (two entries returned two + 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). ``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 + 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, 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 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], ...], + 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/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/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/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/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 new file mode 100644 index 000000000..e0912d040 --- /dev/null +++ b/tests/api/transports/test_direct_http.py @@ -0,0 +1,1310 @@ +from __future__ import annotations + +import asyncio +import json +from dataclasses import replace +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, 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 +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 + + +@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 + + +@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 + + +@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( + "kwargs", + [ + {"refs": (ImageRef(name="00000000-0000-0000-0000-000000000001"),)}, + {"ref_paths": (Path("image.png"),)}, + {"reference_entities": ("entity-1",)}, + {"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 + + +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) + + +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 + # 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", "domain": ".google.com", "path": "/"}] + ) + 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: + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + 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 + + 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] + + # 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 calls == [] + + +@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.google") + 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) + # 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 +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 + + +@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)) + + +@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 + + +_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] + + +@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 + + +_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",)}, # an id with no name: the chip needs both + {"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) + 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"),) + + +# --- 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_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_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 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": "/"}, + # 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] = [] + + 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() + + +# --- 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 == [] + + +@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"),) + + +# --- 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] + + +@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" 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" diff --git a/tests/api/transports/test_frame_builder.py b/tests/api/transports/test_frame_builder.py new file mode 100644 index 000000000..08eb60454 --- /dev/null +++ b/tests/api/transports/test_frame_builder.py @@ -0,0 +1,201 @@ +"""Tests for the pure ogiZ0b frame builder.""" + +from __future__ import annotations + +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 + + +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", + entry_seeds=(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", + "entry_seeds": (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", + entry_seeds=(12345,), + ) + + rpcid, inner, inner_json = _decode_body(body) + + 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] + + +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"]]] + + +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 + + +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/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", diff --git a/tests/e2e/test_direct_image_e2e.py b/tests/e2e/test_direct_image_e2e.py new file mode 100644 index 000000000..2edb0006a --- /dev/null +++ b/tests/e2e/test_direct_image_e2e.py @@ -0,0 +1,308 @@ +"""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"``; 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. + +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 os +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_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", "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) == 3, files + assert all(p.read_bytes().startswith(_JPEG_OR_PNG) for p in files) + assert _image_transports(e2e_env) == ["direct_http"] * 3 + + +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] + + +def test_a_catalogued_reference_routes_to_the_ui_transport( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + """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: + 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", None] + + +@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" + + +def test_a_local_file_reference_is_uploaded_then_generated_directly( + e2e_env: RedactedEnv, tmp_path: Path +) -> None: + """--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 + 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, + "-m", + "gflow_cli", + "image", + "i2i", + "a sailing boat on this blue sea", + "--ref", + str(fresh), + "--project", + project_id, + "--out-file", + str(tmp_path / "boat.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 / "boat.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" + + +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"] 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() 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..db47204a3 --- /dev/null +++ b/tests/features/test_direct_http_transport_steps.py @@ -0,0 +1,121 @@ +"""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", "domain": ".google.com", "path": "/"}] + ) + + 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" 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/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/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: 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 ```