diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d9530e746..22bd52daf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -402,6 +402,7 @@ jobs: # from a local page and drives the model and aspect pickers against it (#1772). # A tenth, test_closed_page_after_click_bdd.py, serves a composer whose submit button closes # the page, and checks a page closed after the click is not a retryable closed browser (#1761). + # The project title readback test intercepts creation and drops the rename reply (#1784). - name: E2E (hermetic subset — route-intercepted, $0, no profile) if: matrix.shard == 'e2e' run: > @@ -416,6 +417,7 @@ jobs: tests/e2e/test_no_spend_e2e.py tests/e2e/test_config_e2e.py tests/e2e/test_catalog_aliases_e2e.py + tests/e2e/test_unconfirmed_project_title_bdd.py --junitxml=pytest-e2e-hermetic.xml - name: E2E-count guard (an empty e2e run is not a passing e2e run) diff --git a/CHANGELOG.md b/CHANGELOG.md index c91d9b6d3..4076779da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- On `flow.google.com`, a new project can keep its saved title when Flow's + rename reply is missing and readback confirms the project. Generation uses that + project and warns about the title: `image t2i`/`i2i --json` and the MCP image, + extend and edit tasks, and video tasks given `project_name`, carry a + `project_title_unconfirmed` warning naming the saved title. If readback fails, the rename error explains + how to reuse the project and reports no generation charge. A browser error during that rename + (a timeout as well as a closed browser) now also ends in that error (exit 7, not retried), + so a retry cannot create a second project ([#1784](https://github.com/ffroliva/gflow-cli/issues/1784)). - The storyboard tool now sends the requested panel count to the model for inline `--tool`, standalone `tools run --panels`, and MCP generation requests. It accepts 1 to 20 panels and defaults to 4 (#1754). diff --git a/docs/ERRORS.md b/docs/ERRORS.md index 02933e3a0..0cf685767 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -200,6 +200,11 @@ place today: `no` / `retry` where nothing was written: a `gflow project create` whose browser closes before Create is clicked, and a standalone `gflow project rename` (renaming again sets the same title). +- When Flow confirms project creation but the title reply is lost, gflow can keep + the saved title after verifying the project. If it cannot verify the project, or + a standalone rename's title remains unconfirmed, `RpcResponseUnavailableError` + reads `no` / `reconcile` and points to the project to check. No generation was + submitted ([#1784](https://github.com/ffroliva/gflow-cli/issues/1784)). - Sites that provably submitted nothing read `no`: the flow.google.com extend editor guard (`none`), the `/about` landing (`reauth`), and both balance-read failures. - On flow.google.com, a gflow error raised before the generation's submit click reads diff --git a/docs/MCP.md b/docs/MCP.md index 1d9ee3fa5..f19e71ba3 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -215,6 +215,11 @@ is [BROWSER_MODES](BROWSER_MODES.md). CLI↔MCP parity is enforced programmatically: `tests/mcp/test_cli_parity.py` walks every CLI leaf command and fails when one has neither a mapped MCP tool nor an explicit exemption with a stated reason. Note the deliberate asymmetry: `gflow_generate_video` has **no** `instructions` param (unlike `gflow_generate_image`) because the video pipeline (`GenerateVideoRequest` / the worker) has no instructions support — agentic-video is a typed divergence, and a dead parameter would be silently dropped. Both `gflow_generate_image` and `gflow_generate_video` support an `out_file` parameter mirroring the CLI `--out-file` flag (#414, #415, #1158), decoding explicit output destinations in the worker path (legacy `output` parameter removed in #1158). Both tools refuse an output path that names a directory (including the output directory itself) with a 400 `Invalid Output` envelope before anything is queued, as the CLI's `--out-file` refuses one ([#1114](https://github.com/ffroliva/gflow-cli/issues/1114)). Unlike the CLI's `--out-file`, an MCP `out_file` — and the `out_dir` of `gflow_download_media`, `gflow_upscale_image` and `gflow_upscale_video` — must resolve **inside the configured output directory** ([`GFLOW_CLI_OUTPUT_DIR`](CONFIGURATION.md#gflow_cli_output_dir)): a relative value is taken relative to it, and a value that resolves outside it (`..`, an absolute path elsewhere, a link leading out) is refused with a 400 `Invalid Output` / `Invalid out_dir` envelope before anything runs. An MCP client may be steered by untrusted content, so it cannot choose where on disk the server writes; for the same reason a tool that opens a browser profile takes `profile` only as a plain name, never a path ([GHSA-hqfj-4jww-76f2](https://github.com/ffroliva/gflow-cli/security/advisories/GHSA-hqfj-4jww-76f2)). `gflow update` is a considered exemption, not a backlog item: the package manager would replace the venv under a live `gflow mcp run` and write its output onto the JSON-RPC stdout channel — the operator runs it and restarts the server. A read-only twin of `gflow update --check` would be harmless; it is the upgrade path if agents ever need version awareness beyond the `initialize` handshake. +When an image, extend or edit task, or a video task given `project_name`, creates a +project on `flow.google.com` and Flow keeps a different saved title, its reply includes a warning +`{"type": "project_title_unconfirmed", "project_id": ..., "saved_title": ..., "message": ...}`. +The generation uses that project. + ### Prompts (Orchestration templates) * `expand_prompt`: Helps the agent structure simple ideas into Google's official 5-component prompt formula (Subject + Action + Location + Composition + Style) before sending them to the generation tools. * `create_character`: Assists agents in defining face, body, and voice parameters for consistent subject generation. diff --git a/docs/USAGE.md b/docs/USAGE.md index c9a8867fe..846f9c3a2 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -1330,6 +1330,13 @@ gflow project show PROJ123 [--json] gflow project rename PROJ123 "Storyboard v2" [--json] ``` +On `flow.google.com`, a newly created project can keep its saved title when the +rename reply is unavailable and gflow can still verify that project. The command +warns about the title and continues with the same project ID; `image t2i` and +`image i2i` add `{"type": "project_title_unconfirmed", "project_id": ..., +"saved_title": ..., "message": ...}` to their `--json` `warnings`. A standalone `project rename` +still requires confirmation of the requested title. + ## Batch video generation (shell loop) `gflow video` has no `batch` subcommand — a manifest-driven video runner @@ -2792,7 +2799,8 @@ use. When set: aspect (`{"type": "aspect_mismatch", "requested": "16:9", "width": 1024, "height": 768}`), a result byte-identical to a local reference image (`{"type": "echoed_reference"}`), and a file under 8 KB (`{"type": "tiny_file", "bytes": 512, "min_bytes": 8192}`). Each - entry carries the image's `media_name` and joins the same `warnings` list; without + entry carries the image's `media_name` and joins the same `warnings` list, after a + `project_title_unconfirmed` entry when a project gflow created kept another title; without `--json` it is a yellow line under the table, and `gflow run` / `gflow image batch` add it to the row. A check never fails the run and never moves or deletes the file. Single-prompt only — `--json` rejects diff --git a/src/gflow_cli/api/dto.py b/src/gflow_cli/api/dto.py index 5a4b153f1..6d5763717 100644 --- a/src/gflow_cli/api/dto.py +++ b/src/gflow_cli/api/dto.py @@ -9,7 +9,7 @@ from __future__ import annotations from collections.abc import Callable -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace from typing import TYPE_CHECKING, Any, Literal, cast if TYPE_CHECKING: @@ -109,6 +109,23 @@ class ProjectInfo: project_id: str title: str + title_unconfirmed: bool = field(default=False, repr=False, compare=False) + + def title_warnings(self) -> list[dict[str, str]]: + """#1784: the result warning for a project Flow saved under another title, else none.""" + if not self.title_unconfirmed: + return [] + return [ + { + "type": "project_title_unconfirmed", + "project_id": self.project_id, + "saved_title": self.title, + "message": ( + "Flow did not confirm the requested title; " + f"the project is saved as {self.title!r}." + ), + } + ] @classmethod def from_create_response(cls, data: dict[str, Any]) -> ProjectInfo: diff --git a/src/gflow_cli/api/image.py b/src/gflow_cli/api/image.py index ff0aaf2ca..6493ec21a 100644 --- a/src/gflow_cli/api/image.py +++ b/src/gflow_cli/api/image.py @@ -235,6 +235,8 @@ def describe_result_warning(warning: Mapping[str, Any]) -> str: return f"Warning: {media} is {got}, not the requested {warning['requested']}." if kind == "echoed_reference": return f"Warning: {media} is byte-identical to a reference image." + if kind == "project_title_unconfirmed": + return f"Warning: {warning['message']}" return f"Warning: {media} is only {warning.get('bytes')} bytes; it may be a placeholder." diff --git a/src/gflow_cli/api/transports/_mc_common.py b/src/gflow_cli/api/transports/_mc_common.py index 485370aa0..4c7290884 100644 --- a/src/gflow_cli/api/transports/_mc_common.py +++ b/src/gflow_cli/api/transports/_mc_common.py @@ -1162,8 +1162,9 @@ async def _project_snapshot( """Read persisted project state in a fresh tab without resetting the composer.""" probe = await page.context.new_page() try: + target = MIGRATED_PROJECT_URL.format(project_id=project_id) await probe.goto( - MIGRATED_PROJECT_URL.format(project_id=project_id), + target, wait_until="domcontentloaded", timeout=45_000, ) @@ -1198,7 +1199,11 @@ async def _project_snapshot( await probe.wait_for_timeout(1000) await probe.reload(wait_until="domcontentloaded", timeout=15_000) await field.wait_for(state="visible", timeout=15_000) - return await field.input_value(), tiles + title = await field.input_value() + if not is_at(probe.url, target): + msg = "Project readback did not stay on the requested project." + raise WireFormatError(detail=msg, charged="no") # a readback bills nothing (#1784) + return title, tiles finally: await probe.close() await page.bring_to_front() # the composer's typing and `@` picker need focus @@ -1650,9 +1655,10 @@ def _write_outcome_unknown( error: TransportTimeoutError | RpcResponseUnavailableError, rpcid: str, hint: str ) -> RpcResponseUnavailableError: """A write whose request was sent but whose result nobody saw: exit 7, never retried - (the class is outside ``RETRYABLE_ERRORS``).""" + (the class is outside ``RETRYABLE_ERRORS``). Only project writes use it, and they bill + nothing (#1784).""" return RpcResponseUnavailableError( - detail=error.detail, route=f"batchexecute:{rpcid}", remediation_hint=hint + detail=error.detail, route=f"batchexecute:{rpcid}", remediation_hint=hint, charged="no" ) diff --git a/src/gflow_cli/api/transports/migrated_composer.py b/src/gflow_cli/api/transports/migrated_composer.py index e393a0b43..a0102e334 100644 --- a/src/gflow_cli/api/transports/migrated_composer.py +++ b/src/gflow_cli/api/transports/migrated_composer.py @@ -849,6 +849,7 @@ async def create_project( ``timeout_s`` bounds the create reply; the selector wait stays at ``ANCHOR_TIMEOUT_S``. Once Create is clicked, a failure never reads as retryable: a lost or late reply is recovered from Flow's navigation to the new project, or is "outcome unknown" (#1037). + If only the rename was unconfirmed, a verified new project can keep its saved title. Leaves ``page`` on the new project, which is where every caller goes next.""" try: await page.goto(MIGRATED_ROOT_URL, wait_until="domcontentloaded", timeout=45_000) @@ -891,6 +892,7 @@ async def create_project( detail="The browser closed during the project create attempt.", route=f"batchexecute:{CREATE_PROJECT_RPC}", remediation_hint=_CREATE_RECOVERY_HINT, + charged="no", ) from exc reply = _as_list_any(payload) project_id: object = reply[0] if reply else None @@ -904,26 +906,99 @@ async def create_project( created: object = names[0] if names else None if title and created != title: try: - await rename_project(page, project_id, title, timeout_s=timeout_s) + created = await rename_project( + page, project_id, title, timeout_s=timeout_s, allow_saved_title=True + ) except retryable_engine_errors() as exc: - if not _is_target_closed(exc): - raise + # The project exists: a retry would create a second one, so always reconcile. + closed = _is_target_closed(exc) raise RpcResponseUnavailableError( - detail="Flow created the project before the browser closed during rename.", + detail=( + "Flow created the project before the browser closed during rename." + if closed + else "Flow created the project, then the browser failed during rename " + f"({type(exc).__name__})." + ), route=f"batchexecute:{RENAME_PROJECT_RPC}", remediation_hint=f"Reuse the existing project with --project {project_id}.", + charged="no", ) from exc - created = title - return ProjectInfo(project_id=project_id, title=str(created or "")) + return ProjectInfo( + project_id=project_id, + title=str(created or ""), + title_unconfirmed=bool(title and created != title), + ) + + +def _require_rename_page(page: Page, target: str, project_id: str) -> None: + if not is_at(page.url, target): + raise WireFormatError( + detail="Flow left the requested project before its title could be saved.", + route=f"batchexecute:{RENAME_PROJECT_RPC}", + charged="no", + remediation_hint=f"Check the title at {target} and reuse --project {project_id}.", + ) + + +async def _recover_rename( + page: Page, + project_id: str, + title: str, + original_error: RpcResponseUnavailableError | TransportTimeoutError, + *, + allow_saved_title: bool, +) -> str: + """Settle a lost rename reply by reading the saved title back (#992, #1037, #1784). + + Returns the saved title: the requested one, or, when ``allow_saved_title``, the one Flow + kept. Anything unproven raises the outcome-unknown error.""" + target = MIGRATED_PROJECT_URL.format(project_id=project_id) + unknown = _write_outcome_unknown( + original_error, + RENAME_PROJECT_RPC, + f"The rename was sent but not confirmed. Check the title at {target} " + f"and reuse the project with --project {project_id}.", + ) + try: + persisted_title, _ = await _project_snapshot(page, project_id) + except Exception: # noqa: BLE001 - no readback means the outcome stays unknown + raise unknown from original_error + project_page_unavailable = allow_saved_title and ( + page.is_closed() or not is_at(page.url, target) + ) + title_unconfirmed = persisted_title != title + if project_page_unavailable or ( + title_unconfirmed and (not allow_saved_title or not persisted_title.strip()) + ): + raise unknown from original_error + if title_unconfirmed: + log.warning( + "migrated.project_title_unconfirmed", + project_id=project_id, + message="The new project is available under its saved title.", + ) + else: + log.info( + "migrated.project_rename_recovered", + project_id=project_id, + after=type(original_error).__name__, + ) + return persisted_title async def rename_project( - page: Page, project_id: str, title: str, *, timeout_s: float = PAGE_RPC_TIMEOUT_S -) -> None: + page: Page, + project_id: str, + title: str, + *, + timeout_s: float = PAGE_RPC_TIMEOUT_S, + allow_saved_title: bool = False, +) -> str: """Rename a project through its header title on flow.google.com. ``timeout_s`` bounds the rename reply; the selector wait stays at ``ANCHOR_TIMEOUT_S``. - A lost or late reply is settled by reading the saved title back (#992, #1037).""" + A lost or late reply is settled by reading the saved title back (#992, #1037). + Only creation may keep the saved title instead of confirming the requested name.""" target = MIGRATED_PROJECT_URL.format(project_id=project_id) if not is_at(getattr(page, "url", ""), target): await page.goto(target, wait_until="domcontentloaded", timeout=45_000) @@ -936,16 +1011,21 @@ async def rename_project( at="migrated.rename_project", timeout_s=min(timeout_s, ANCHOR_TIMEOUT_S), ) + _require_rename_page(page, target, project_id) - if await field.input_value() == title: - persisted_title, _ = await _project_snapshot(page, project_id) - if persisted_title == title: - log.info("migrated.project_title_unchanged", project_id=project_id) - return + if ( + await field.input_value() == title + and (await _project_snapshot(page, project_id))[0] == title + ): + _require_rename_page(page, target, project_id) + log.info("migrated.project_title_unchanged", project_id=project_id) + return title async def submit() -> None: try: + _require_rename_page(page, target, project_id) await field.fill(title, timeout=15_000) + _require_rename_page(page, target, project_id) await field.press("Enter", timeout=15_000) except PlaywrightTimeoutError as e: raise UiSelectorDriftError( @@ -959,25 +1039,12 @@ async def submit() -> None: try: payload = await rpc_reply(page, RENAME_PROJECT_RPC, submit, timeout_s=timeout_s, write=True) except (RpcResponseUnavailableError, TransportTimeoutError) as original_error: - unknown = _write_outcome_unknown( - original_error, - RENAME_PROJECT_RPC, - f"The rename was sent but not confirmed. Project {project_id} exists; open it " - "on https://flow.google.com/ to check its title, and reuse it with " - f"--project {project_id} rather than creating another.", - ) - try: - persisted_title, _ = await _project_snapshot(page, project_id) - except Exception: # noqa: BLE001 - no readback means the outcome stays unknown - raise unknown from original_error - if persisted_title != title: - raise unknown from original_error - payload = [persisted_title] - log.info( - "migrated.project_rename_recovered", - project_id=project_id, - after=type(original_error).__name__, + saved = await _recover_rename( + page, project_id, title, original_error, allow_saved_title=allow_saved_title ) + if saved != title: + return saved + payload = [saved] echo = _as_list_any(payload) echoed: object = echo[0] if echo else None if echoed != title: @@ -986,6 +1053,7 @@ async def submit() -> None: route=f"batchexecute:{RENAME_PROJECT_RPC}", ) log.info("migrated.project_renamed", project_id=project_id) + return title #: The app's own balance read: no arguments, fired on every load of the app (#795). diff --git a/src/gflow_cli/cli_image.py b/src/gflow_cli/cli_image.py index 0f5d46131..5d98f69d0 100644 --- a/src/gflow_cli/cli_image.py +++ b/src/gflow_cli/cli_image.py @@ -1267,7 +1267,10 @@ async def _run_t2i( operation_kind="t2i", undownloaded=undownloaded, ) - checks = saved_images_warnings(req, images, saved_paths) # #1534 + checks = [ # #1534, #1784 + *project.title_warnings(), + *saved_images_warnings(req, images, saved_paths), + ] if output_format == OutputFormat.ID.value: for img in images[: len(saved_paths)]: @@ -1825,7 +1828,10 @@ async def _generate( project=project, generate=_generate, ) - checks = saved_images_warnings(req, images, saved_paths, local_refs) # #1534 + checks = [ # #1534, #1784 + *project.title_warnings(), + *saved_images_warnings(req, images, saved_paths, local_refs), + ] if output_format == OutputFormat.ID.value: for img in images[: len(saved_paths)]: diff --git a/src/gflow_cli/cli_project.py b/src/gflow_cli/cli_project.py index 576906287..5e2bdda69 100644 --- a/src/gflow_cli/cli_project.py +++ b/src/gflow_cli/cli_project.py @@ -181,7 +181,7 @@ async def _run_create_project( def create_subcommand( title: str | None, profile: str | None, output_format: str, as_json: bool ) -> None: - """Create a fresh Flow project with dual-side title synchronization.""" + """Create a fresh Flow project and report its saved title.""" profile_name = _resolve_profile(profile) provider_dir = _make_provider_dir(profile_name) diff --git a/src/gflow_cli/mcp/tools.py b/src/gflow_cli/mcp/tools.py index c549fb750..afc1a7f74 100644 --- a/src/gflow_cli/mcp/tools.py +++ b/src/gflow_cli/mcp/tools.py @@ -1057,8 +1057,9 @@ def _build_video_media_inputs( "the reCAPTCHA token; other shapes open a visible browser (browser_visibility " "overrides). The result names route, visibility and retried. " "Returns local file paths to the generated images; fewer than count adds images_missing " - "to warnings, and a saved image off the requested aspect, identical to a reference " - "or under 8 KB adds aspect_mismatch, echoed_reference or tiny_file." + "to warnings, a saved image off the requested aspect, identical to a reference or under " + "8 KB adds aspect_mismatch, echoed_reference or tiny_file, and a new project Flow saved " + "under another title adds project_title_unconfirmed." ), ) @_guarded @@ -1292,7 +1293,7 @@ async def gflow_generate_image( "catalog records in project with a caption; it is bound on the UI path with no upload, " "while a cross-project UUID (or un-captioned UUID with a local fallback) returns the " "exit-36 envelope and an uncatalogued/unusable UUID returns 400. " - "Returns the local file path; a model Flow is retiring adds model_retiring to warnings." + "Returns the local path; warnings may carry model_retiring or project_title_unconfirmed." ), ) @_guarded diff --git a/src/gflow_cli/mcp/video_edit_tools.py b/src/gflow_cli/mcp/video_edit_tools.py index b7ad5d40c..4286be288 100644 --- a/src/gflow_cli/mcp/video_edit_tools.py +++ b/src/gflow_cli/mcp/video_edit_tools.py @@ -136,7 +136,7 @@ def _preflight_edit_inputs( # noqa: PLR0913 "preserve source aspect at 720p, and refuse reference_images (exit 11, not ported " "yet: download the clip with gflow data download and pass the file). " "out_file, if given, must resolve inside the configured output directory. " - "Returns the local file path; a model Flow is retiring adds model_retiring to warnings." + "Returns the local path; warnings may carry model_retiring or project_title_unconfirmed." ), ) @common._guarded # pyright: ignore[reportPrivateUsage] diff --git a/src/gflow_cli/mcp/video_extend_tools.py b/src/gflow_cli/mcp/video_extend_tools.py index d99ec39dc..02d28a901 100644 --- a/src/gflow_cli/mcp/video_extend_tools.py +++ b/src/gflow_cli/mcp/video_extend_tools.py @@ -184,7 +184,7 @@ def _preflight_extend_inputs( "Drives Flow's Extend control in a headless browser by default; browser_visibility " "'headed' shows the window (so does the server's GFLOW_CLI_TRANSPORT=ui_automation). " "Spends video credits; returns the local file path to the extended clip, with route " - "('ui'), visibility and retried." + "('ui'), visibility and retried; warnings may carry project_title_unconfirmed." ), ) @common._guarded # pyright: ignore[reportPrivateUsage] diff --git a/src/gflow_cli/worker/daemon.py b/src/gflow_cli/worker/daemon.py index 7b2a5cb6e..1bb76d7ee 100644 --- a/src/gflow_cli/worker/daemon.py +++ b/src/gflow_cli/worker/daemon.py @@ -266,7 +266,7 @@ async def process_task(self, task: QueueTask) -> None: # Mutable holder so the observer sees the project id once it is resolved — # an image task may auto-create its Flow project inside the client block. checkpoint_project_id: list[str | None] = [task.payload.get("project_id")] - tool_warnings: list[dict[str, str]] = [] + pre_submit_warnings: list[dict[str, str]] = [] def save_checkpoint( phase: str, @@ -295,7 +295,7 @@ def save_checkpoint( workflow_ids=workflow_ids, catalog_operation_id=catalog_operation_id, missing_media_ids=missing_media_ids, - result_warnings=[*(result_warnings or ()), *tool_warnings], + result_warnings=[*(result_warnings or ()), *pre_submit_warnings], ) except Exception as exc: logger.warning( @@ -305,18 +305,23 @@ def save_checkpoint( exc_info=exc, ) - def _save_tool_warnings() -> None: - """Persist a prompt-tool fallback now: a task that fails before the submit - checkpoint (or between it and the next one) must still reply with it.""" - if tool_warnings: + def _save_pre_submit_warnings() -> None: + """Keep these warnings even if the task fails before submitting.""" + if pre_submit_warnings: save_checkpoint("claimed", may_have_spent=False) + def _use_created_project(project: ProjectInfo) -> str: + checkpoint_project_id[0] = project.project_id + pre_submit_warnings.extend(project.title_warnings()) + _save_pre_submit_warnings() + return project.project_id + observe_checkpoint = self._checkpoint_observer( task.task_id, claimant, checkpoint_project_id, save_checkpoint, - result_warnings=tool_warnings, + result_warnings=pre_submit_warnings, ) # Pre-submit checkpoint: nothing spent yet. A crash/cancel before the @@ -375,17 +380,13 @@ def _save_tool_warnings() -> None: # the CLI); this read was `project_title`, which nothing has ever # written, so every agent-supplied name was silently dropped (#628). project_title = task.payload.get("project_name", "gflow-cli images") - project_created = False + project_created = not project_id if project_id: project_flow_id = project_id project = ProjectInfo(project_id=project_id, title=project_title) else: project = await client.create_project(title=project_title) - project_flow_id = project.project_id - project_created = True - # Now that the project is resolved, the observer can persist - # it (the credit-free video recovery key; harmless for images). - checkpoint_project_id[0] = project_flow_id + project_flow_id = _use_created_project(project) # Resolve @-mentions and expand --tool specs (shared helper). from gflow_cli.services.mentions import resolve_and_apply @@ -397,9 +398,9 @@ def _save_tool_warnings() -> None: project_id=project_flow_id, tool_specs=tuple(task.payload.get("tool_specs", ())), quiet=True, - warning_sink=tool_warnings, + warning_sink=pre_submit_warnings, ) - _save_tool_warnings() + _save_pre_submit_warnings() async def _generate(request: GenerateImageRequest) -> list[GeneratedImage]: if count == 1: @@ -564,7 +565,7 @@ async def _generate(request: GenerateImageRequest) -> list[GeneratedImage]: project_name = task.payload.get("project_name") if project_id is None and project_name: created = await client.create_project(title=project_name) - project_id = created.project_id + project_id = _use_created_project(created) # Resolve @-mentions and expand --tool specs (shared helper). from gflow_cli.services.mentions import resolve_and_apply @@ -575,9 +576,9 @@ async def _generate(request: GenerateImageRequest) -> list[GeneratedImage]: project_id=project_id, tool_specs=tuple(task.payload.get("tool_specs", ())), quiet=True, - warning_sink=tool_warnings, + warning_sink=pre_submit_warnings, ) - _save_tool_warnings() + _save_pre_submit_warnings() def on_started(started: VideoStarted) -> None: started_media_ids.append(started.media_id) @@ -640,12 +641,16 @@ def on_started(started: VideoStarted) -> None: # Kept for the failure record below: the edit's prompt and model. req = task.decoded.request if task.decoded is not None else None run_clip_task = { - "extend": self._run_video_extend_task, + "extend": partial( + self._run_video_extend_task, + use_created_project=_use_created_project, + ), "edit": partial( self._run_video_edit_task, built_requests=built_requests, - tool_warnings=tool_warnings, - save_tool_warnings=_save_tool_warnings, + pre_submit_warnings=pre_submit_warnings, + save_pre_submit_warnings=_save_pre_submit_warnings, + use_created_project=_use_created_project, ), "movie": self._run_movie_task, }[task.task_type] @@ -897,6 +902,7 @@ async def _run_video_extend_task( # noqa: PLR0913 checkpoint_project_id: list[str | None], started_media_ids: list[str], observe_checkpoint: Callable[[GenerationCheckpoint], None], + use_created_project: Callable[[ProjectInfo], str], ) -> str: req = ( cast("MigratedExtendRequest", task.decoded.request) @@ -938,10 +944,11 @@ async def _run_video_extend_task( # noqa: PLR0913 visibility=visibility, ) as client: if project_id is None: - created = await client.create_project( - title=project_name or slugify_project_name(req.prompt) + project_id = use_created_project( + await client.create_project( + title=project_name or slugify_project_name(req.prompt) + ) ) - project_id = created.project_id checkpoint_project_id[0] = project_id resolved_project = str(project_id) @@ -1010,8 +1017,9 @@ async def _run_video_edit_task( # noqa: PLR0913 started_media_ids: list[str], observe_checkpoint: Callable[[GenerationCheckpoint], None], built_requests: list[Any], - tool_warnings: list[dict[str, str]], - save_tool_warnings: Callable[[], None], + pre_submit_warnings: list[dict[str, str]], + save_pre_submit_warnings: Callable[[], None], + use_created_project: Callable[[ProjectInfo], str], ) -> str: from gflow_cli._cli_helpers import apply_tool_option # noqa: PLC0415 from gflow_cli.api.transports.migrated_video_edit import ( # noqa: PLC0415 @@ -1043,10 +1051,10 @@ async def _run_video_edit_task( # noqa: PLR0913 tool_specs, category="video", quiet=True, - warning_sink=tool_warnings, + warning_sink=pre_submit_warnings, ) req = replace(req, prompt=prompt_to_send, original_prompt=orig, tool=applied) - save_tool_warnings() + save_pre_submit_warnings() built_requests.append(req) def on_started(started: VideoStarted) -> None: @@ -1069,10 +1077,11 @@ def on_started(started: VideoStarted) -> None: settings=settings, ) as client: if project_id is None: - created = await client.create_project( - title=task.payload.get("project_name") or slugify_project_name(req.prompt) + project_id = use_created_project( + await client.create_project( + title=task.payload.get("project_name") or slugify_project_name(req.prompt) + ) ) - project_id = created.project_id checkpoint_project_id[0] = project_id result = await client.edit_video( req=req, diff --git a/tests/api/transports/fixtures/migrated_composer_contract.json b/tests/api/transports/fixtures/migrated_composer_contract.json index b35b874c7..37214b195 100644 --- a/tests/api/transports/fixtures/migrated_composer_contract.json +++ b/tests/api/transports/fixtures/migrated_composer_contract.json @@ -130,7 +130,7 @@ "_interpolation_body_problem": "function (body: 'str', rpcid: 'str', start_media_id: 'str | None', end_media_id: 'str | None', prompt: 'str | None' = None) -> 'str | None' sha=8a16fb21967ecd99", "_ligature": "function (page: 'Any', name: 'str') -> 'Any' sha=6dbbb5aa3089b887", "_navigated_project_id": "function (url: 'str', before: 'str') -> 'str | None' sha=2497784af52c6199", - "_project_snapshot": "function (page: 'Page', project_id: 'str', *, upload_name: 'str | None' = None) -> 'tuple[str, list[dict[str, str]]]' sha=c259640096b1d429", + "_project_snapshot": "function (page: 'Page', project_id: 'str', *, upload_name: 'str | None' = None) -> 'tuple[str, list[dict[str, str]]]' sha=5aa5573552c65e7b", "_r2v_body_problem": "function (body: 'str', rpcid: 'str', media_ids: 'tuple[str, ...]', prompt: 'str | None' = None) -> 'str | None' sha=358f4e072356bf36", "_raise_if_out_of_credits": "function (page: 'Any') -> 'None' sha=14dd7d39d50e69c8", "_recovery_detail": "function (page: 'Page', pressed: 'bool | None', error: 'Exception') -> 'str' sha=1b0e30519af9d350", @@ -139,12 +139,12 @@ "_unported_image_form": "function (request: 'GenerateImageRequest') -> 'str | None' sha=a0dd8ba1e6f93910", "_wait_anchor": "function (page: 'Page', selector: 'str', *, named: 'str', requested: 'str', at: 'str', timeout_s: 'float') -> 'Any' sha=f60a4cf05096f7db", "body_rpcid": "function (body: 'str') -> 'str | None' sha=2742321c5304b2a9", - "create_project": "function (page: 'Page', title: 'str', *, timeout_s: 'float' = 120.0) -> 'ProjectInfo' sha=2444a3d3977cb072", + "create_project": "function (page: 'Page', title: 'str', *, timeout_s: 'float' = 120.0) -> 'ProjectInfo' sha=d8f009f9833ba444", "is_at": "function (url: 'object', target: 'str') -> 'bool' sha=d918ccf22f0049f8", "migrated_can_serve": "function (request: 'GenerateVideoRequest', project_id: 'str | None') -> 'bool' sha=6fff5b8bfd0295b6", "migrated_images_prefer": "function (request: 'GenerateImageRequest', *, page_url: 'str | None' = None, project_id: 'str | None' = None) -> 'bool' sha=3402dae1831304be", "read_credits": "function (page: 'Page', *, timeout_s: 'float' = 30.0) -> 'CreditsInfo' sha=4621d1eff7d83fff", - "rename_project": "function (page: 'Page', project_id: 'str', title: 'str', *, timeout_s: 'float' = 120.0) -> 'None' sha=e9a2a042b205d021", + "rename_project": "function (page: 'Page', project_id: 'str', title: 'str', *, timeout_s: 'float' = 120.0, allow_saved_title: 'bool' = False) -> 'str' sha=317f19b9d331846e", "request_body": "function (request: 'Any') -> 'str' sha=5bd59f1d6a05e9c7", "rpc_reply": "function (page: 'Page', rpcid: 'str', action: 'Callable[[], Awaitable[None]]', *, timeout_s: 'float', write: 'bool' = False, accept: 'Callable[[Any], bool] | None' = None) -> 'Any' sha=501c1df69835b67c", "run_images": "function (page: 'Page', request: 'GenerateImageRequest', *, project_id: 'str | None', out_dir: 'Path | None' = None, name_resolver: 'Callable[[str], str | None] | None' = None) -> 'list[GeneratedImage]' sha=88c7455fbe9ada5e", @@ -154,13 +154,13 @@ "public_functions": { "attach_submit_evidence": "function (exc: 'Exception', *, quoted_credits: 'int | None', started_ids: 'list[str]') -> 'None' sha=99c1fd4343807c34", "body_rpcid": "function (body: 'str') -> 'str | None' sha=2742321c5304b2a9", - "create_project": "function (page: 'Page', title: 'str', *, timeout_s: 'float' = 120.0) -> 'ProjectInfo' sha=2444a3d3977cb072", + "create_project": "function (page: 'Page', title: 'str', *, timeout_s: 'float' = 120.0) -> 'ProjectInfo' sha=d8f009f9833ba444", "finish_video_result": "function (composer: 'MigratedComposer', page: 'Page', record: 'GenerationRecord', *, project_id: 'str', quoted_credits: 'int | None', save: 'ClipSaver', download: 'bool') -> 'VideoResult' sha=338ba979410a41eb", "is_at": "function (url: 'object', target: 'str') -> 'bool' sha=d918ccf22f0049f8", "migrated_can_serve": "function (request: 'GenerateVideoRequest', project_id: 'str | None') -> 'bool' sha=6fff5b8bfd0295b6", "migrated_images_prefer": "function (request: 'GenerateImageRequest', *, page_url: 'str | None' = None, project_id: 'str | None' = None) -> 'bool' sha=3402dae1831304be", "read_credits": "function (page: 'Page', *, timeout_s: 'float' = 30.0) -> 'CreditsInfo' sha=4621d1eff7d83fff", - "rename_project": "function (page: 'Page', project_id: 'str', title: 'str', *, timeout_s: 'float' = 120.0) -> 'None' sha=e9a2a042b205d021", + "rename_project": "function (page: 'Page', project_id: 'str', title: 'str', *, timeout_s: 'float' = 120.0, allow_saved_title: 'bool' = False) -> 'str' sha=317f19b9d331846e", "request_body": "function (request: 'Any') -> 'str' sha=5bd59f1d6a05e9c7", "rpc_reply": "function (page: 'Page', rpcid: 'str', action: 'Callable[[], Awaitable[None]]', *, timeout_s: 'float', write: 'bool' = False, accept: 'Callable[[Any], bool] | None' = None) -> 'Any' sha=501c1df69835b67c", "run_images": "function (page: 'Page', request: 'GenerateImageRequest', *, project_id: 'str | None', out_dir: 'Path | None' = None, name_resolver: 'Callable[[str], str | None] | None' = None) -> 'list[GeneratedImage]' sha=88c7455fbe9ada5e", diff --git a/tests/api/transports/test_migrated_project.py b/tests/api/transports/test_migrated_project.py index 03214ee9c..74c9a0711 100644 --- a/tests/api/transports/test_migrated_project.py +++ b/tests/api/transports/test_migrated_project.py @@ -16,7 +16,14 @@ import pytest from gflow_cli.api.transports import migrated_composer as mc -from gflow_cli.errors import TransportTimeoutError, UiSelectorDriftError, WireFormatError +from gflow_cli.errors import ( + FlowAppError, + RpcResponseUnavailableError, + TransportTimeoutError, + UiSelectorDriftError, + WireFormatError, + is_retryable, +) PID = "57c099ee-a5d6-4e2d-83c9-0346f9644b09" @@ -130,6 +137,9 @@ def __init__(self, *, url: str = "about:blank") -> None: self.locator_handlers_disabled = False # a promo the handler cannot close self.keyboard = self + def is_closed(self) -> bool: + return False + async def add_locator_handler(self, locator: _Loc, handler: Any, **_: Any) -> None: if not self.locator_handlers_disabled: self.locator_handlers[locator.sel] = handler @@ -195,6 +205,7 @@ async def test_create_reads_id_and_title_from_the_rpc_reply() -> None: assert info.project_id == PID assert info.title == "my film" + assert info.title_unconfirmed is False assert page.gotos[0] == "https://flow.google.com/" assert page.clicks == [mc.NEW_PROJECT_BUTTON] assert page.filled == "my film" # the requested title was applied by rename @@ -206,9 +217,151 @@ async def test_create_skips_rename_when_the_reply_already_carries_the_title() -> info = await mc.create_project(page, "my film") # type: ignore[arg-type] assert info.title == "my film" + assert info.title_unconfirmed is False assert page.filled is None +@pytest.mark.parametrize("redirect_at", ["navigation", "fill"]) +async def test_create_does_not_submit_rename_from_another_project( + monkeypatch: pytest.MonkeyPatch, redirect_at: str +) -> None: + page = _page_creating() + page.on_enter = (_batch(mc.RENAME_PROJECT_RPC), _frame("o8DA4", ["wanted"])) + target = mc.MIGRATED_PROJECT_URL.format(project_id=PID) + other = mc.MIGRATED_PROJECT_URL.format(project_id="22222222-2222-4222-8222-222222222222") + if redirect_at == "navigation": + page.navigate_on_create = other + original_goto = page.goto + + async def redirected_goto(url: str, **kwargs: Any) -> None: + await original_goto(other if url == target else url, **kwargs) + + monkeypatch.setattr(page, "goto", redirected_goto) + else: + original_fill = _Loc.fill + + async def fill_then_redirect(locator: _Loc, value: str, **kwargs: Any) -> None: + await original_fill(locator, value, **kwargs) + page.url = other + + monkeypatch.setattr(_Loc, "fill", fill_then_redirect) + + with pytest.raises(WireFormatError) as exc: + await mc.create_project(page, "wanted", timeout_s=0.02) # type: ignore[arg-type] + + assert (exc.value.charged, exc.value.next_action) == ("no", "reconcile") + assert PID in exc.value.remediation_hint + assert len(page.action_timeouts) == (1 if redirect_at == "fill" else 0) + assert page.clicks == [mc.NEW_PROJECT_BUTTON] + + +@pytest.mark.parametrize("reply_is_unreadable", [False, True]) +async def test_create_keeps_verified_project_when_only_the_title_is_unconfirmed( + monkeypatch: pytest.MonkeyPatch, reply_is_unreadable: bool +) -> None: + from unittest.mock import AsyncMock + + from structlog.testing import capture_logs + + page = _page_creating(title="Flow default") + if reply_is_unreadable: + page.on_enter = (_batch(mc.RENAME_PROJECT_RPC), None) + readback = AsyncMock(return_value=("Flow default", [])) + monkeypatch.setattr(mc, "_project_snapshot", readback) + + with capture_logs() as logs: + info = await mc.create_project(page, "wanted", timeout_s=0.02) # type: ignore[arg-type] + + assert (info.project_id, info.title) == (PID, "Flow default") + assert info.title_unconfirmed + assert page.clicks == [mc.NEW_PROJECT_BUTTON] + assert len(page.action_timeouts) == 2 # one fill, one Enter + readback.assert_awaited_once_with(page, PID) + assert any( + event["event"] == "migrated.project_title_unconfirmed" and event["log_level"] == "warning" + for event in logs + ) + + +@pytest.mark.parametrize("readback_title", [None, "Flow default", "wanted"]) +async def test_create_stops_without_a_usable_project_after_rename( + monkeypatch: pytest.MonkeyPatch, readback_title: str | None +) -> None: + page = _page_creating() + + async def readback(*_args: Any) -> tuple[str, list[dict[str, str]]]: + if readback_title is not None: + page.url = mc.MIGRATED_ROOT_URL + return readback_title, [] + raise RuntimeError("project could not be read") + + monkeypatch.setattr(mc, "_project_snapshot", readback) + with pytest.raises(RpcResponseUnavailableError) as exc: + await mc.create_project(page, "wanted", timeout_s=0.02) # type: ignore[arg-type] + + assert exc.value.charged == "no" + assert exc.value.next_action == "reconcile" + assert not is_retryable(exc.value) + assert PID in exc.value.remediation_hint + assert page.clicks == [mc.NEW_PROJECT_BUTTON] + + +@pytest.mark.parametrize("saved", ["", " "]) +async def test_create_does_not_keep_a_project_whose_saved_title_is_blank( + monkeypatch: pytest.MonkeyPatch, saved: str +) -> None: + from unittest.mock import AsyncMock + + page = _page_creating(title="Flow default") + monkeypatch.setattr(mc, "_project_snapshot", AsyncMock(return_value=(saved, []))) + + with pytest.raises(RpcResponseUnavailableError) as exc: + await mc.create_project(page, "wanted", timeout_s=0.02) # type: ignore[arg-type] + + assert exc.value.charged == "no" + assert PID in exc.value.remediation_hint + + +async def test_create_does_not_keep_a_project_whose_page_closed_during_readback( + monkeypatch: pytest.MonkeyPatch, +) -> None: + page = _page_creating(title="Flow default") + + async def readback(*_args: Any) -> tuple[str, list[dict[str, str]]]: + page.is_closed = lambda: True # type: ignore[method-assign] + return "Flow default", [] + + monkeypatch.setattr(mc, "_project_snapshot", readback) + + with pytest.raises(RpcResponseUnavailableError) as exc: + await mc.create_project(page, "wanted", timeout_s=0.02) # type: ignore[arg-type] + + assert exc.value.charged == "no" + + +@pytest.mark.parametrize("closed", [True, False]) +async def test_a_browser_error_renaming_a_created_project_names_it_and_is_not_retried( + monkeypatch: pytest.MonkeyPatch, closed: bool +) -> None: + # The project already exists: a retry would create a second one, so the caller must + # reconcile with the id instead, whether the browser closed or only timed out. + from playwright.async_api import Error as PwError + from playwright.async_api import TimeoutError as PwTimeout + + async def failing_rename(*_: Any, **__: Any) -> str: + if closed: + raise PwError("Target page, context or browser has been closed") + raise PwTimeout("Timeout 15000ms exceeded") + + monkeypatch.setattr(mc, "rename_project", failing_rename) + with pytest.raises(RpcResponseUnavailableError) as exc: + await mc.create_project(_page_creating(title="Flow default"), "wanted", timeout_s=0.02) # type: ignore[arg-type] + + assert (exc.value.charged, exc.value.next_action) == ("no", "reconcile") + assert not is_retryable(exc.value) + assert PID in exc.value.remediation_hint + + async def test_create_without_the_fab_is_drift_naming_the_anchor() -> None: page = _page_creating() page.present[mc.NEW_PROJECT_BUTTON] = False @@ -279,6 +432,23 @@ async def test_create_click_blocked_by_an_overlay_names_it( await mc.create_project(page, "x", timeout_s=0.1) # type: ignore[arg-type] +async def test_browser_closing_during_create_is_outcome_unknown_charging_nothing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The click may have reached Flow, so the outcome is unknown; a project bills nothing. + from playwright.async_api import Error as PwError + + from gflow_cli.errors import RpcResponseUnavailableError + + async def closed(*_: Any) -> None: + raise PwError("Target page, context or browser has been closed") + + monkeypatch.setattr(mc, "_click_create", closed) + with pytest.raises(RpcResponseUnavailableError, match="browser closed") as exc: + await mc.create_project(FakePage(), "x", timeout_s=0.1) # type: ignore[arg-type] + assert (exc.value.charged, exc.value.next_action) == ("no", "reconcile") + + async def test_create_click_timeout_after_the_request_left_is_outcome_unknown() -> None: # Flow may have made the project, so this is never drift, and never retryable (#1037). from gflow_cli.errors import RpcResponseUnavailableError, is_retryable @@ -334,6 +504,7 @@ async def test_create_with_no_reply_and_no_navigation_is_outcome_unknown() -> No assert not isinstance(exc.value, TransportTimeoutError) assert not is_retryable(exc.value) assert exit_code_for(exc.value) == 7 + assert exc.value.charged == "no" # a project create bills nothing (#1784) assert "--project" in exc.value.remediation_hint assert page.clicks == [mc.NEW_PROJECT_BUTTON] # never clicked twice @@ -391,6 +562,22 @@ async def test_rename_without_the_title_input_is_drift() -> None: await mc.rename_project(page, PID, "t", timeout_s=0.1) # type: ignore[arg-type] +async def test_standalone_rename_keeps_the_known_landing_diagnosis( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from unittest.mock import AsyncMock + + page = FakePage(url="https://flow.google.com/about") + page.present[mc.PROJECT_TITLE_INPUT] = False + monkeypatch.setattr(page, "goto", AsyncMock()) + + with pytest.raises(FlowAppError) as exc: + await mc.rename_project(page, PID, "wanted", timeout_s=0.02) # type: ignore[arg-type] + + assert (exc.value.charged, exc.value.next_action) == ("no", "reauth") + assert not page.action_timeouts + + def test_anchors_are_structural_not_labels() -> None: """AGENTS.md locale-invariance: no display text in these selectors.""" assert "flow-projects-page" in mc.NEW_PROJECT_BUTTON @@ -462,10 +649,31 @@ async def test_rename_to_the_current_title_needs_no_rpc(monkeypatch: pytest.Monk monkeypatch.setattr(mc, "_project_snapshot", AsyncMock(return_value=("already saved", []))) page = FakePage(url=f"https://flow.google.com/project/{PID}") page.current_title = "already saved" - await mc.rename_project(page, PID, "already saved", timeout_s=0.01) # type: ignore[arg-type] + saved = await mc.rename_project(page, PID, "already saved", timeout_s=0.01) # type: ignore[arg-type] + assert saved == "already saved" assert page.filled is None and not page._handlers +async def test_rename_to_the_current_title_refuses_a_page_that_left_the_project( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Callers keep typing into `page` after a rename; it must still be this project. + page = FakePage(url=f"https://flow.google.com/project/{PID}") + page.current_title = "already saved" + + async def readback(*_args: Any) -> tuple[str, list[dict[str, str]]]: + page.url = mc.MIGRATED_ROOT_URL + return "already saved", [] + + monkeypatch.setattr(mc, "_project_snapshot", readback) + + with pytest.raises(WireFormatError) as exc: + await mc.rename_project(page, PID, "already saved", timeout_s=0.01) # type: ignore[arg-type] + + assert exc.value.charged == "no" + assert page.filled is None + + async def test_local_title_alone_does_not_prove_rename_saved( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -612,10 +820,12 @@ class _Probe: def __init__(self, reads: list[list[dict[str, str]]], title: str) -> None: self.reads, self.title = reads, title self.gotos: list[str] = [] + self.url = "about:blank" self.reloads = 0 self.closed = False async def goto(self, url: str, **_: Any) -> None: + self.url = url self.gotos.append(url) def locator(self, _sel: str) -> _Field: @@ -681,6 +891,22 @@ async def test_snapshot_gives_up_at_its_deadline_and_still_closes( assert probe.closed and owner.fronted +async def test_snapshot_that_leaves_the_project_charges_nothing() -> None: + # A readback is a read: whatever page Flow lands it on, nothing can have been billed (#1784). + probe = _Probe([[]], title="t") + original_goto = probe.goto + + async def redirected(url: str, **kw: Any) -> None: + await original_goto(mc.MIGRATED_ROOT_URL, **kw) + + probe.goto = redirected # type: ignore[method-assign] + owner = _Owner(probe) + with pytest.raises(WireFormatError) as exc: + await mc._project_snapshot(owner, PID) # type: ignore[arg-type] + assert exc.value.charged == "no" + assert probe.closed and owner.fronted + + async def test_snapshot_closes_the_probe_when_reading_fails() -> None: probe = _Probe([], title="t") @@ -778,6 +1004,7 @@ async def test_rename_timeout_without_proof_is_outcome_unknown( with pytest.raises(RpcResponseUnavailableError, match=mc.RENAME_PROJECT_RPC) as exc: await mc.rename_project(page, PID, "wanted", timeout_s=0.02) # type: ignore[arg-type] assert not is_retryable(exc.value) + assert exc.value.charged == "no" assert PID in exc.value.remediation_hint diff --git a/tests/cli/test_cli_image.py b/tests/cli/test_cli_image.py index 9f0fc3723..eea63b99b 100644 --- a/tests/cli/test_cli_image.py +++ b/tests/cli/test_cli_image.py @@ -619,6 +619,42 @@ def test_json_warns_when_images_are_missing( {"type": "images_missing", "requested": 2, "returned": 1} ] + @pytest.mark.parametrize( + "args", + [["t2i", "a cat"], ["i2i", "a cat", "--ref", "11111111-1111-1111-1111-111111111111"]], + ) + def test_json_warns_when_flow_kept_another_project_title( + self, runner: CliRunner, tmp_path: Path, args: list[str] + ) -> None: + """#1784: the requested title did not stick; the run succeeds and says so.""" + import json as _json + + from gflow_cli.api.dto import ProjectInfo + + client = _make_t2i_client(images=[_make_generated_image(media_name="m1")]) + client.create_project.return_value = ProjectInfo( + "proj-x", "Flow default", title_unconfirmed=True + ) + with ( + patch("gflow_cli.cli_image.FlowApiClient", return_value=client), + patch("gflow_cli.cli_image._make_provider_dir", return_value=tmp_path / "prof"), + patch("gflow_cli.cli_image._resolve_profile", return_value="default"), + ): + from gflow_cli.cli import main + + result = runner.invoke( + main, + ["image", *args, "--json", "--out", str(tmp_path / "out")], + catch_exceptions=False, + ) + + assert result.exit_code == 0, result.output + warnings = _json.loads(result.stdout)["warnings"] + unconfirmed = [w for w in warnings if w["type"] == "project_title_unconfirmed"] + assert [(w["project_id"], w["saved_title"]) for w in unconfirmed] == [ + ("proj-x", "Flow default") + ] + class TestImageI2I: def test_i2i_attaches_local_ref_paths(self, runner: CliRunner, tmp_path: Path) -> None: diff --git a/tests/e2e/test_unconfirmed_project_title_bdd.py b/tests/e2e/test_unconfirmed_project_title_bdd.py new file mode 100644 index 000000000..99f3f70c5 --- /dev/null +++ b/tests/e2e/test_unconfirmed_project_title_bdd.py @@ -0,0 +1,125 @@ +"""A real browser with every request intercepted. No account or Flow writes.""" + +from __future__ import annotations + +import asyncio +import json +from collections import Counter +from typing import Any +from urllib.parse import parse_qs, urlsplit + +from playwright.async_api import Page, Route, async_playwright +from pytest_bdd import given, scenarios, then, when + +from gflow_cli.api.transports import migrated_composer as mc +from gflow_cli.errors import RpcResponseUnavailableError, is_retryable + +scenarios("../features/unconfirmed_project_title.feature") + +_PROJECT = "11111111-1111-4111-8111-111111111111" +_OTHER = "22222222-2222-4222-8222-222222222222" +_ROOT = """ +""" +_PROJECT_PAGE = """ +""" + + +@given("readback opens the same project", target_fixture="readback_project") +def same_project() -> str: + return _PROJECT + + +@given("readback opens a different project", target_fixture="readback_project") +def other_project() -> str: + return _OTHER + + +@when("Flow confirms creation and drops the title reply", target_fixture="outcome") +def lose_title_reply(readback_project: str) -> tuple[Any, Counter[str]]: + counts: Counter[str] = Counter() + + async def drive() -> Any: + async with async_playwright() as pw: + browser = await pw.chromium.launch( + headless=True, + args=["--host-resolver-rules=MAP flow.google.com ~NOTFOUND"], + ) + try: + context = await browser.new_context() + owner = await context.new_page() + probes: list[Page] = [] + + def remember_probe(probe: Page) -> None: + probes.append(probe) + + context.on("page", remember_probe) + + async def respond(route: Route) -> None: + url = urlsplit(route.request.url) + rpc = parse_qs(url.query).get("rpcids", [""])[0] + if rpc == mc.CREATE_PROJECT_RPC: + counts["create"] += 1 + payload = json.dumps([_PROJECT, ["Flow default"]]) + frame = [["wrb.fr", rpc, payload, None, None, None, "generic"]] + await route.fulfill(body=")]}'\n10\n" + json.dumps(frame) + "\n") + elif rpc == mc.RENAME_PROJECT_RPC: + counts["rename"] += 1 + await route.abort() + elif url.path == "/": + await route.fulfill(body=_ROOT, content_type="text/html") + elif url.path == f"/project/{_PROJECT}": + body = _PROJECT_PAGE + if route.request.frame.page != owner and readback_project != _PROJECT: + # Stay inside the intercepted response, including the wrong-path case. + body = ( + "{body}" + ) + await route.fulfill(body=body, content_type="text/html") + else: + counts["unexpected"] += 1 + await route.abort() + + await context.route("**/*", respond) + try: + result = await mc.create_project(owner, "Wanted title", timeout_s=1.0) + except RpcResponseUnavailableError as exc: + result = exc + (probe,) = probes + assert urlsplit(probe.url).path == f"/project/{readback_project}" + assert probe.is_closed() + return result + finally: + await browser.close() + + return asyncio.run(drive()), counts + + +@then("the created project is returned with its saved title") +def project_is_kept(outcome: tuple[Any, Counter[str]]) -> None: + project, _ = outcome + assert (project.project_id, project.title) == (_PROJECT, "Flow default") + assert project.title_unconfirmed + + +@then("the response asks to reconcile without a generation charge") +def reconcile(outcome: tuple[Any, Counter[str]]) -> None: + error, _ = outcome + assert isinstance(error, RpcResponseUnavailableError) + assert (error.charged, error.next_action) == ("no", "reconcile") + assert _PROJECT in error.remediation_hint + assert not is_retryable(error) + + +@then("only one create and one rename were attempted") +def writes_not_repeated(outcome: tuple[Any, Counter[str]]) -> None: + _, counts = outcome + assert counts == {"create": 1, "rename": 1} diff --git a/tests/features/unconfirmed_project_title.feature b/tests/features/unconfirmed_project_title.feature new file mode 100644 index 000000000..ab70fd868 --- /dev/null +++ b/tests/features/unconfirmed_project_title.feature @@ -0,0 +1,13 @@ +@e2e @e2e_auth +Feature: A missing title reply after project creation (#1784) + Scenario: The saved project is still available + Given readback opens the same project + When Flow confirms creation and drops the title reply + Then the created project is returned with its saved title + And only one create and one rename were attempted + + Scenario: Readback redirects to a different project + Given readback opens a different project + When Flow confirms creation and drops the title reply + Then the response asks to reconcile without a generation charge + And only one create and one rename were attempted diff --git a/tests/mcp/test_video_edit_tool.py b/tests/mcp/test_video_edit_tool.py index 4838a565e..5314d6f9c 100644 --- a/tests/mcp/test_video_edit_tool.py +++ b/tests/mcp/test_video_edit_tool.py @@ -8,6 +8,7 @@ import pytest +from gflow_cli.api.dto import ProjectInfo from gflow_cli.api.video import EditVideoRequest, VideoModel, VideoResult, VideoStatus from gflow_cli.config import reset_settings from gflow_cli.data.models import OperationKind, OperationStatus @@ -170,8 +171,9 @@ async def test_mcp_edit_video_validation_and_confinement( @pytest.mark.asyncio +@pytest.mark.parametrize("creates_project", [False, True]) async def test_worker_processes_edit_task_end_to_end( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, creates_project: bool ) -> None: db_path = tmp_path / "gflow.db" clip = tmp_path / "in.mp4" @@ -195,6 +197,10 @@ async def __aenter__(self) -> _FakeClient: async def __aexit__(self, *_exc: Any) -> None: return None + async def create_project(self, *, title: str) -> ProjectInfo: + # #1784: Flow kept its default title; the task must say so. + return ProjectInfo(_PID, "Flow default", title_unconfirmed=True) + async def edit_video(self, **kwargs: Any) -> VideoResult: if kwargs.get("on_started"): from gflow_cli.api.video import VideoStarted @@ -208,6 +214,7 @@ async def edit_video(self, **kwargs: Any) -> VideoResult: quoted_credits=9, ) + project = {"project_name": "Reel"} if creates_project else {"project_id": _PID} try: with DataStore.open(db_path) as store: DataRepository(store).upsert_profile("p1", tmp_path / "home" / "profile_p1") @@ -219,7 +226,7 @@ async def edit_video(self, **kwargs: Any) -> VideoResult: "schema_version": 1, "prompt": "lantern glow", "source_video": str(clip), - "project_id": _PID, + **project, "model": "omni-1.2", "output_file": str(dest), }, @@ -240,6 +247,12 @@ async def edit_video(self, **kwargs: Any) -> VideoResult: ) assert op is not None assert op.status == OperationStatus.SUCCEEDED + warned = [ + w["project_id"] + for w in codec.task_warnings(done).get("warnings", []) + if w["type"] == "project_title_unconfirmed" + ] + assert warned == ([_PID] if creates_project else []) finally: worker.close() finally: diff --git a/tests/mcp/test_video_extend_tool.py b/tests/mcp/test_video_extend_tool.py index f0913b6a5..a7176b107 100644 --- a/tests/mcp/test_video_extend_tool.py +++ b/tests/mcp/test_video_extend_tool.py @@ -513,3 +513,69 @@ async def test_worker_extend_credit_cap_error_persists_exit_45( assert row.error is not None assert row.error["exit_code"] == 45 assert row.error["charged"] == "no" + + +@pytest.mark.asyncio +async def test_worker_extend_warns_when_flow_kept_another_project_title( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """#1784: an extend task that creates its project reports a title Flow did not confirm.""" + from gflow_cli.api.dto import ProjectInfo + + db_path = tmp_path / "gflow.db" + monkeypatch.setenv("GFLOW_CLI_DB_PATH", str(db_path)) + monkeypatch.setenv("GFLOW_CLI_PROFILES_DIR", str(tmp_path / "profiles")) + (tmp_path / "profiles" / "default").mkdir(parents=True) + reset_settings() + + class _Client: + async def __aenter__(self) -> _Client: + return self + + async def __aexit__(self, *_exc: object) -> None: + return None + + async def create_project(self, *, title: str) -> ProjectInfo: + return ProjectInfo(PROJECT, "Flow default", title_unconfirmed=True) + + async def extend_video_migrated(self, **kwargs: Any) -> tuple[ExtendOutcome, Any]: + assert kwargs["project_id"] == PROJECT + rec = GenerationRecord(workflow_id="wf", project_id=PROJECT, media_id=MEDIA, status=3) + outcome = ExtendOutcome( + record=rec, + video=b"\x00\x00\x00\x18ftypmp42\x00\x00", + model_key="macaron_cookie_extend_4s", + aspect="16:9", + scene_id=None, + quoted_credits=12, + source_media_id=MEDIA, + ) + return outcome, tmp_path / "extended.mp4" + + with DataStore.open(db_path) as store: + DataRepository(store).upsert_profile("default", tmp_path / "profiles" / "default") + q = QueueRepository(store) + q.enqueue_task( + "ext-title", + "default", + "extend", + {"schema_version": 1, "prompt": "go", "source_media_id": MEDIA, "project_name": "Reel"}, + ) + claimed = q.claim_task("ext-title", "test") + assert claimed is not None + + worker = FlowWorker("default", str(db_path)) + try: + with patch("gflow_cli.worker.daemon.FlowApiClient", return_value=_Client()): + await worker.process_task(claimed) + done = worker.repo.get_task("ext-title") + finally: + worker.close() + + assert done is not None and done.status == "completed" + warned = [ + w["project_id"] + for w in codec.task_warnings(done).get("warnings", []) + if w["type"] == "project_title_unconfirmed" + ] + assert warned == [PROJECT] diff --git a/tests/test_image_result_checks.py b/tests/test_image_result_checks.py index 515896331..53a86a7e6 100644 --- a/tests/test_image_result_checks.py +++ b/tests/test_image_result_checks.py @@ -12,7 +12,7 @@ from rich.console import Console from gflow_cli import image_batch, json_output -from gflow_cli.api.dto import GeneratedImage +from gflow_cli.api.dto import GeneratedImage, ProjectInfo from gflow_cli.api.image import ( Aspect, GenerateImageRequest, @@ -142,6 +142,10 @@ def test_only_the_saved_prefix_of_a_partial_result_is_checked(tmp_path: Path) -> ), ({"type": "echoed_reference"}, "byte-identical to a reference image"), ({"type": "tiny_file", "bytes": 12}, "only 12 bytes"), + ( + ProjectInfo("p", "Flow default", title_unconfirmed=True).title_warnings()[0], + "Flow did not confirm the requested title; the project is saved as 'Flow default'.", + ), ], ) def test_each_warning_has_a_console_line(warning: dict[str, Any], text: str) -> None: diff --git a/tests/worker/test_daemon.py b/tests/worker/test_daemon.py index c6b94b0df..a5d145999 100644 --- a/tests/worker/test_daemon.py +++ b/tests/worker/test_daemon.py @@ -218,8 +218,20 @@ async def test_a_short_reply_keeps_the_numbered_output_file( @pytest.mark.asyncio +@pytest.mark.parametrize( + ("project_name", "saved_title", "title_unconfirmed"), + [ + ("Client pitch deck", "Client pitch deck", False), + ("Client pitch deck", "Flow default", True), + (None, "gflow-cli Dec 05, 09:00 PM", False), + (None, "Flow default", True), + ], +) async def test_an_agent_supplied_project_name_becomes_the_created_project_title( temp_db: DataStore, + project_name: str | None, + saved_title: str, + title_unconfirmed: bool, ) -> None: """#628: the daemon must read the key the MCP tool actually writes. @@ -229,34 +241,47 @@ async def test_an_agent_supplied_project_name_becomes_the_created_project_title( ever written — so the name was dropped on every call and each fresh project was created as the hardcoded fallback instead. """ + from gflow_cli.api.dto import ProjectInfo + from gflow_cli.worker import codec + repo = QueueRepository(temp_db) task = repo.enqueue_task( task_id="task-project-name", profile_name="default", task_type="t2i", - payload={"prompt": "a lighthouse", "count": 2, "project_name": "Client pitch deck"}, + payload={"prompt": "a lighthouse", "count": 2, "project_name": project_name}, ) worker = FlowWorker("default", str(temp_db.path)) fake_client = FakeFlowApiClient() - fake_client.create_project.return_value = MagicMock( - project_id="project-abc", title="Client pitch deck" + fake_client.create_project.return_value = ProjectInfo( + "project-abc", saved_title, title_unconfirmed=title_unconfirmed ) fake_client.generate_images_batch.return_value = [FakeGeneratedImage(media_name="media-1")] with patch("gflow_cli.worker.daemon.FlowApiClient", return_value=fake_client): await worker.process_task(task) - fake_client.create_project.assert_awaited_once_with(title="Client pitch deck") + fake_client.create_project.assert_awaited_once_with(title=project_name) + assert fake_client.generate_images_batch.await_args.kwargs["project_id"] == "project-abc" + completed = repo.get_task(task.task_id) + assert completed is not None and completed.status == "completed" + warning_types = [w["type"] for w in codec.task_warnings(completed).get("warnings", [])] + assert ("project_title_unconfirmed" in warning_types) == title_unconfirmed worker.close() @pytest.mark.asyncio +@pytest.mark.parametrize("title_unconfirmed", [False, True]) async def test_an_agent_supplied_project_name_titles_the_video_project_too( - temp_db: DataStore, + temp_db: DataStore, title_unconfirmed: bool ) -> None: """#864: the MCP video tool writes ``project_name`` exactly as the image tool does, - and ``gflow video t2v --project-name`` honours it — the video branch read nothing.""" + and ``gflow video t2v --project-name`` honours it — the video branch read nothing. + #1784: a title Flow did not confirm is reported as a task warning.""" + from gflow_cli.api.dto import ProjectInfo + from gflow_cli.worker import codec + repo = QueueRepository(temp_db) task = repo.enqueue_task( task_id="task-t2v-project-name", @@ -267,7 +292,9 @@ async def test_an_agent_supplied_project_name_titles_the_video_project_too( worker = FlowWorker("default", str(temp_db.path)) fake_client = FakeFlowApiClient() - fake_client.create_project.return_value = MagicMock(project_id="project-v", title="Client reel") + fake_client.create_project.return_value = ProjectInfo( + "project-v", "Client reel", title_unconfirmed=title_unconfirmed + ) fake_client.generate_video.return_value = _completed_video_result("media-v") with patch("gflow_cli.worker.daemon.FlowApiClient", return_value=fake_client): @@ -275,6 +302,11 @@ async def test_an_agent_supplied_project_name_titles_the_video_project_too( fake_client.create_project.assert_awaited_once_with(title="Client reel") assert fake_client.generate_video.await_args.kwargs["project_id"] == "project-v" + completed = repo.get_task(task.task_id) + assert completed is not None and completed.status == "completed" + warnings = codec.task_warnings(completed).get("warnings", []) + unconfirmed = [w for w in warnings if w["type"] == "project_title_unconfirmed"] + assert [w["project_id"] for w in unconfirmed] == (["project-v"] if title_unconfirmed else []) worker.close() diff --git a/website/docs/ERRORS.md b/website/docs/ERRORS.md index 02933e3a0..0cf685767 100644 --- a/website/docs/ERRORS.md +++ b/website/docs/ERRORS.md @@ -200,6 +200,11 @@ place today: `no` / `retry` where nothing was written: a `gflow project create` whose browser closes before Create is clicked, and a standalone `gflow project rename` (renaming again sets the same title). +- When Flow confirms project creation but the title reply is lost, gflow can keep + the saved title after verifying the project. If it cannot verify the project, or + a standalone rename's title remains unconfirmed, `RpcResponseUnavailableError` + reads `no` / `reconcile` and points to the project to check. No generation was + submitted ([#1784](https://github.com/ffroliva/gflow-cli/issues/1784)). - Sites that provably submitted nothing read `no`: the flow.google.com extend editor guard (`none`), the `/about` landing (`reauth`), and both balance-read failures. - On flow.google.com, a gflow error raised before the generation's submit click reads diff --git a/website/docs/MCP.md b/website/docs/MCP.md index 1d9ee3fa5..f19e71ba3 100644 --- a/website/docs/MCP.md +++ b/website/docs/MCP.md @@ -215,6 +215,11 @@ is [BROWSER_MODES](BROWSER_MODES.md). CLI↔MCP parity is enforced programmatically: `tests/mcp/test_cli_parity.py` walks every CLI leaf command and fails when one has neither a mapped MCP tool nor an explicit exemption with a stated reason. Note the deliberate asymmetry: `gflow_generate_video` has **no** `instructions` param (unlike `gflow_generate_image`) because the video pipeline (`GenerateVideoRequest` / the worker) has no instructions support — agentic-video is a typed divergence, and a dead parameter would be silently dropped. Both `gflow_generate_image` and `gflow_generate_video` support an `out_file` parameter mirroring the CLI `--out-file` flag (#414, #415, #1158), decoding explicit output destinations in the worker path (legacy `output` parameter removed in #1158). Both tools refuse an output path that names a directory (including the output directory itself) with a 400 `Invalid Output` envelope before anything is queued, as the CLI's `--out-file` refuses one ([#1114](https://github.com/ffroliva/gflow-cli/issues/1114)). Unlike the CLI's `--out-file`, an MCP `out_file` — and the `out_dir` of `gflow_download_media`, `gflow_upscale_image` and `gflow_upscale_video` — must resolve **inside the configured output directory** ([`GFLOW_CLI_OUTPUT_DIR`](CONFIGURATION.md#gflow_cli_output_dir)): a relative value is taken relative to it, and a value that resolves outside it (`..`, an absolute path elsewhere, a link leading out) is refused with a 400 `Invalid Output` / `Invalid out_dir` envelope before anything runs. An MCP client may be steered by untrusted content, so it cannot choose where on disk the server writes; for the same reason a tool that opens a browser profile takes `profile` only as a plain name, never a path ([GHSA-hqfj-4jww-76f2](https://github.com/ffroliva/gflow-cli/security/advisories/GHSA-hqfj-4jww-76f2)). `gflow update` is a considered exemption, not a backlog item: the package manager would replace the venv under a live `gflow mcp run` and write its output onto the JSON-RPC stdout channel — the operator runs it and restarts the server. A read-only twin of `gflow update --check` would be harmless; it is the upgrade path if agents ever need version awareness beyond the `initialize` handshake. +When an image, extend or edit task, or a video task given `project_name`, creates a +project on `flow.google.com` and Flow keeps a different saved title, its reply includes a warning +`{"type": "project_title_unconfirmed", "project_id": ..., "saved_title": ..., "message": ...}`. +The generation uses that project. + ### Prompts (Orchestration templates) * `expand_prompt`: Helps the agent structure simple ideas into Google's official 5-component prompt formula (Subject + Action + Location + Composition + Style) before sending them to the generation tools. * `create_character`: Assists agents in defining face, body, and voice parameters for consistent subject generation. diff --git a/website/docs/USAGE.md b/website/docs/USAGE.md index e88b408fb..46d1fe66d 100644 --- a/website/docs/USAGE.md +++ b/website/docs/USAGE.md @@ -1330,6 +1330,13 @@ gflow project show PROJ123 [--json] gflow project rename PROJ123 "Storyboard v2" [--json] ``` +On `flow.google.com`, a newly created project can keep its saved title when the +rename reply is unavailable and gflow can still verify that project. The command +warns about the title and continues with the same project ID; `image t2i` and +`image i2i` add `{"type": "project_title_unconfirmed", "project_id": ..., +"saved_title": ..., "message": ...}` to their `--json` `warnings`. A standalone `project rename` +still requires confirmation of the requested title. + ## Batch video generation (shell loop) `gflow video` has no `batch` subcommand — a manifest-driven video runner @@ -2792,7 +2799,8 @@ use. When set: aspect (`{"type": "aspect_mismatch", "requested": "16:9", "width": 1024, "height": 768}`), a result byte-identical to a local reference image (`{"type": "echoed_reference"}`), and a file under 8 KB (`{"type": "tiny_file", "bytes": 512, "min_bytes": 8192}`). Each - entry carries the image's `media_name` and joins the same `warnings` list; without + entry carries the image's `media_name` and joins the same `warnings` list, after a + `project_title_unconfirmed` entry when a project gflow created kept another title; without `--json` it is a yellow line under the table, and `gflow run` / `gflow image batch` add it to the row. A check never fails the run and never moves or deletes the file. Single-prompt only — `--json` rejects