diff --git a/CHANGELOG.md b/CHANGELOG.md index f1c05ab80..7e2621e05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,13 @@ history. ### Changed +- `comfy workflow save --where cloud` prints a link that opens only the saved + workflow (`?workflowId=`) when Cloud's `/api/features` has + `private_saved_file_links_enabled` on. The workflow id is the one record + Cloud made from the saved file. With the setting off, or when that record + is missing, not unique, or the search for it fails, the link opens the + folder as before. The receipt adds `url_opens` (`workflow` or `folder`) and + `folder_link_reason`. - Release watches poll through `stopping` and report `build_stopped` (exit 1) when a release stops. Log following reads the final lines after `stopped` and exits successfully. - `comfy deploy status` explains beside its sampled counts that they may lag after workers scale down. The deploy-failure guidance also clarifies that sampled counts cannot establish whether a worker or job is running now. @@ -64,7 +71,7 @@ history. uploads with `--no-upload` and then uploads only the approved files with `--allow-upload`, and the agent runs one real job before it saves with `comfy workflow save --where cloud` and - hands back the folder link (or says there is none for a record-only save). + hands back the save's link (or says there is none for a record-only save). `comfy_cli/skills/comfy-run-on-cloud/PROMPT-TEMPLATE.md` is the prompt local ComfyUI's Copy prompt button gives the agent. `comfy-build` points a single-workflow request at the new skill, `comfy-build-failures` says a diff --git a/comfy_cli/command/workflow.py b/comfy_cli/command/workflow.py index 9522b3928..82c67beb6 100644 --- a/comfy_cli/command/workflow.py +++ b/comfy_cli/command/workflow.py @@ -1408,6 +1408,7 @@ def _local_delete(renderer, target, workflow_id: str) -> None: # userdata file in a folder of its own instead (Cloud mirrors that file into # a workflow record by itself) and prints a link that opens the folder. Any # other answer, or no answer, keeps the record-only save exactly as before. +# Workflow-id links: docs/adr/SIDEBAR-0013-link-a-cloud-save-to-the-workflow-it-made.md. # The file is written with ``overwrite=false``, so nothing that exists is # ever replaced: a name already taken moves on to `` (2)``, ``(3)``, ... # Only a frontend-format workflow goes into a folder, since the sidebar opens @@ -1421,6 +1422,7 @@ def _local_delete(renderer, target, workflow_id: str) -> None: # --------------------------------------------------------------------------- _CLI_CLOUD_SAVE_FLAG = "cli_cloud_save_enabled" +_WORKFLOW_LINKS_FLAG = "private_saved_file_links_enabled" # How long the flag read may take before ``save`` keeps the record-only path. _FEATURES_TIMEOUT_S = 10.0 @@ -1465,18 +1467,24 @@ def _request_errors() -> tuple[type[BaseException], ...]: ) -def _cli_cloud_save_enabled(target) -> bool: - """True only when Cloud's ``/api/features`` answers ``cli_cloud_save_enabled: true``. +def _cloud_save_features(target) -> dict[str, Any]: + """Cloud's ``/api/features`` reply, or ``{}`` when it cannot be read. - A missing key, any other value, or a request that fails in any way reads - as off, so ``save`` keeps its record-only path and ``delete`` its - record-only delete. + A flag counts as on only when its value is a JSON ``true``; a missing + key, any other value, or a request that fails in any way reads as off, so + ``save`` keeps its record-only path and ``delete`` its record-only delete. + ``save`` reads both of its flags from this one reply. """ try: _, body = _http_request(target.url("features"), target, timeout=_FEATURES_TIMEOUT_S) except _request_errors(): - return False - return isinstance(body, dict) and body.get(_CLI_CLOUD_SAVE_FLAG) is True + return {} + return body if isinstance(body, dict) else {} + + +def _cli_cloud_save_enabled(target) -> bool: + """True only when Cloud's ``/api/features`` answers ``cli_cloud_save_enabled: true``.""" + return _cloud_save_features(target).get(_CLI_CLOUD_SAVE_FLAG) is True def _cloud_folder_name(name: str) -> str: @@ -1565,13 +1573,36 @@ def _cloud_records_named(target, name: str) -> list[dict] | None: return None -def _cloud_saved_record(target, name: str) -> dict | None: - """The record Cloud mirrored a new file into, or None when it cannot be told.""" +# The first half of the ``workflow_record_unknown`` message, by the reason +# ``_cloud_saved_record`` gives. +_RECORD_UNKNOWN_CLAUSES = { + "record_not_found": "Cloud did not show the workflow record it made from it", + "record_ambiguous": "Cloud shows more than one workflow record of its name", + "record_lookup_failed": "the search for the workflow record Cloud made from it failed", +} + + +def _cloud_saved_record(target, name: str) -> tuple[dict | None, str | None]: + """The record Cloud mirrored a new file into, or None and why it cannot be told. + + The reason is ``record_not_found`` (no live record has the name: Cloud's + copy into its workflow records is best-effort), ``record_ambiguous`` + (more than one has it) or ``record_lookup_failed`` (the search failed, + ran past its page cap, or sent a row with no usable id). + """ try: rows = _cloud_records_named(target, name) except _request_errors(): - return None - return rows[0] if rows and len(rows) == 1 else None + return None, "record_lookup_failed" + if rows is None: + return None, "record_lookup_failed" + if not rows: + return None, "record_not_found" + if len(rows) > 1: + return None, "record_ambiguous" + if not isinstance(rows[0].get("id"), str) or not rows[0]["id"]: + return None, "record_lookup_failed" + return rows[0], None def _cloud_link_id(value: Any) -> str | None: @@ -1587,9 +1618,13 @@ def _cloud_workspace_id(target) -> str | None: return _cloud_link_id(body.get("id")) if isinstance(body, dict) else None -def _cloud_folder_link(target, *, workspace_id: str | None, folder: str, deployment: str) -> str | None: - """The Cloud editor link that opens ``folder``, or None for an unusable base URL. +def _cloud_save_link( + target, *, workspace_id: str | None, folder: str, deployment: str, workflow_id: str | None = None +) -> str | None: + """The Cloud editor link for a sidebar save, or None for an unusable base URL. + With ``workflow_id`` the link opens that one workflow record + (``workflowId=``); without it, every workflow in ``folder``. ``deployment`` is a deployment id, or ``standard`` for Comfy Cloud itself. It goes in only with the workspace, since the editor reads it only then. """ @@ -1601,7 +1636,10 @@ def _cloud_folder_link(target, *, workspace_id: str | None, folder: str, deploym query: dict[str, str] = {} if workspace_id: query["workspace"] = workspace_id - query[_WORKFLOWS_DIR] = folder + if workflow_id: + query["workflowId"] = workflow_id + else: + query[_WORKFLOWS_DIR] = folder if workspace_id: query["deployment"] = deployment encoded = urllib.parse.urlencode(query, quote_via=urllib.parse.quote) @@ -1617,6 +1655,7 @@ def _cloud_folder_save( name: str, description: str | None, deployment: str | None, + workflow_links: bool, ) -> None: """Write the workflow as ``workflows//.json`` and print its link. @@ -1624,6 +1663,7 @@ def _cloud_folder_save( record already has the name the file would mirror into (``/``): Cloud adds a version to a record of that name, so writing there would change a workflow that already exists. + ``workflow_links``: docs/adr/SIDEBAR-0013-link-a-cloud-save-to-the-workflow-it-made.md. """ import urllib.error @@ -1670,13 +1710,22 @@ def _cloud_folder_save( except (ValueError, RecursionError): pass record_name = key[: -len(".json")] - record = _cloud_saved_record(target, record_name) - workflow_id = record.get("id") if record and isinstance(record.get("id"), str) else None - latest_version = record.get("latest_version") if record and workflow_id else None + record, record_unknown = _cloud_saved_record(target, record_name) + workflow_id = record["id"] if record else None + latest_version = record.get("latest_version") if record else None workspace_id = _cloud_workspace_id(target) - url = _cloud_folder_link( - target, workspace_id=workspace_id, folder=folder, deployment=deployment or _STANDARD_DEPLOYMENT + link_workflow_id = workflow_id if workflow_links else None + url = _cloud_save_link( + target, + workspace_id=workspace_id, + folder=folder, + deployment=deployment or _STANDARD_DEPLOYMENT, + workflow_id=link_workflow_id, ) + url_opens = None if url is None else ("workflow" if link_workflow_id else "folder") + folder_link_reason = None + if url_opens == "folder": + folder_link_reason = record_unknown if workflow_links else "workflow_links_off" # ``workflow_id``, ``name``, ``latest_version`` and ``source`` keep their # record-save meaning: the id is the record Cloud mirrored the file into, # which `workflow get` and `workflow delete` take. @@ -1687,6 +1736,8 @@ def _cloud_folder_save( "filename": f"{_WORKFLOWS_DIR}/{key}", "folder": folder, "url": url, + "url_opens": url_opens, + "folder_link_reason": folder_link_reason, "workspace_id": workspace_id, "deployment": deployment or _STANDARD_DEPLOYMENT, "source": str(path), @@ -1706,16 +1757,18 @@ def _cloud_folder_save( warnings.append( { "code": "workspace_unknown", - "message": "Cloud did not say which workspace the save went to, so the link opens the folder in " - "the browser's current workspace", + "message": f"Cloud did not say which workspace the save went to, so the link opens the {url_opens} " + "in the browser's current workspace", } ) if workflow_id is None: + why = _RECORD_UNKNOWN_CLAUSES[record_unknown] warnings.append( { "code": "workflow_record_unknown", - "message": "the file is saved, but Cloud did not show the workflow record it made from it, so " - "workflow_id is null; find it with `comfy --json workflow list --name` and the saved name", + "message": f"the file is saved, but {why}, so workflow_id is null" + + (" and the link opens the folder" if url_opens == "folder" and workflow_links else "") + + "; find it with `comfy --json workflow list --name` and the saved name", } ) if warnings: @@ -2043,7 +2096,7 @@ def save_cmd( "--deployment", show_default=False, help="Cloud, when the save goes to a sidebar folder: the deployment id the printed link opens the " - "folder on. Default `standard`, Comfy Cloud itself.", + "workflow or folder on. Default `standard`, Comfy Cloud itself.", ), ] = None, where: Annotated[str | None, typer.Option("--where", show_default=False)] = None, @@ -2092,10 +2145,18 @@ def save_cmd( # ``nodes[]``; an API-format file there would open empty. So only a # frontend-format workflow goes into a folder, and an API-format one keeps # the record-only save with a warning that says why it has no link. - sidebar = _cli_cloud_save_enabled(target) + features = _cloud_save_features(target) + sidebar = features.get(_CLI_CLOUD_SAVE_FLAG) is True if sidebar and _is_frontend_format(workflow_json): return _cloud_folder_save( - renderer, target, path=path, text=text, name=name, description=description, deployment=deployment + renderer, + target, + path=path, + text=text, + name=name, + description=description, + deployment=deployment, + workflow_links=features.get(_WORKFLOW_LINKS_FLAG) is True, ) body: dict[str, Any] = {"name": name, "workflow_json": workflow_json} diff --git a/comfy_cli/error_codes.py b/comfy_cli/error_codes.py index 4d3d091aa..a3fb4164b 100644 --- a/comfy_cli/error_codes.py +++ b/comfy_cli/error_codes.py @@ -1034,16 +1034,20 @@ class ErrorCode: ErrorCode( "workspace_unknown", "`comfy workflow save` wrote to a Comfy Cloud Workflows-sidebar folder, but Cloud did not say which " - "workspace it went to, so `data.url` leaves out the workspace and deployment and opens the folder in " - "whatever workspace the browser is on. Surfaced in `data.warnings[]` (not as an error envelope) " - "because the save itself succeeded.", + "workspace it went to, so `data.url` leaves out the workspace and deployment and opens the workflow or " + "folder (`data.url_opens`) in whatever workspace the browser is on. Surfaced in `data.warnings[]` (not " + "as an error envelope) because the save itself succeeded.", "switch the browser to the workspace `comfy cloud whoami` shows before opening the link", ), ErrorCode( "workflow_record_unknown", "`comfy workflow save` wrote to a Comfy Cloud Workflows-sidebar folder, but Cloud did not show the " "workflow record it makes from that file, so `data.workflow_id` and `data.latest_version` are null. " - "Surfaced in `data.warnings[]` (not as an error envelope) because the file itself was saved.", + "`data.folder_link_reason` says why when workflow links are on: `record_not_found` (Cloud's copy " + "into its workflow records is best-effort and made none), `record_ambiguous` (more than one record " + "has the name) or `record_lookup_failed` (the search failed). The link then opens the folder instead " + "of the workflow. Surfaced in `data.warnings[]` (not as an error envelope) because the file itself " + "was saved.", "find the record with `comfy --json workflow list --name `", ), ErrorCode( diff --git a/comfy_cli/skills/comfy-run-on-cloud/SKILL.md b/comfy_cli/skills/comfy-run-on-cloud/SKILL.md index 394226dc9..d433b6e0f 100644 --- a/comfy_cli/skills/comfy-run-on-cloud/SKILL.md +++ b/comfy_cli/skills/comfy-run-on-cloud/SKILL.md @@ -336,11 +336,27 @@ comfy --json workflow save --name '' --where cloud --deployment &workflows=&deployment=`. If `data.url` -is missing, the save is a record only: nothing was added to the Workflows -sidebar and there is no link. Say that plainly, give `data.workflow_id`, and do -not point them at a sidebar entry. Then read `data.warnings[]` for the reason: +file. Hand back `data.url` as returned. `data.url_opens` says what it opens in +the person's workspace: + +- `workflow`: only the saved workflow, + `?workspace=&workflowId=&deployment=`. + Cloud checks the link against the saved file when it opens. +- `folder`: every workflow in the new folder, + `?workspace=&workflows=&deployment=`. + `data.folder_link_reason` says why: `workflow_links_off` (the workspace does + not give workflow links), or `record_not_found`, `record_ambiguous` or + `record_lookup_failed` (the save could not tell which workflow Cloud made + from the file, and `data.warnings[]` carries `workflow_record_unknown`). + +Treat a `data.url_opens` or `data.folder_link_reason` value not listed here as +`folder`: later versions may add values. + +If `data.url` is missing and `data.filename` is set, the file is in the +sidebar but the CLI could not build a link from the Cloud base URL; give +`data.filename`. If both are missing, the save is a record only: nothing was +added to the Workflows sidebar and there is no link. Say that plainly, give +`data.workflow_id`, and do not point them at a sidebar entry. Then read `data.warnings[]` for the reason: - `api_format_saved_as_record`: sidebar saving is on, but the file is in API format, which the sidebar cannot open. Save the editor-format file instead diff --git a/comfy_cli/skills/comfy/SKILL.md b/comfy_cli/skills/comfy/SKILL.md index 218de59ec..41f3e9597 100644 --- a/comfy_cli/skills/comfy/SKILL.md +++ b/comfy_cli/skills/comfy/SKILL.md @@ -721,7 +721,13 @@ When the cloud workspace has `cli_cloud_save_enabled` on (`GET /api/features`), file into a new folder in the Cloud Workflows sidebar, named after `--name` (` (2)` and so on when the folder has files or a workflow of that name exists; nothing is ever replaced), and `data.url` is a link that opens that -folder. `data.workflow_id` is still the saved workflow's id. The link opens +folder. `data.workflow_id` is still the saved workflow's id. When +`private_saved_file_links_enabled` is also on, the link opens only that +workflow (`workflowId=`) instead; `data.url_opens` is +`workflow` or `folder`, and for a folder link `data.folder_link_reason` says +why (`workflow_links_off`, `record_not_found`, `record_ambiguous`, +`record_lookup_failed`); treat a value not listed here as `folder`. Hand back +`data.url` as returned. The link opens Comfy Cloud itself unless `--deployment ` names a build. `data.warnings[]` may carry `description_ignored`, `workspace_unknown` or `workflow_record_unknown`. An API-format workflow keeps the record-only save, diff --git a/docs/adr/SIDEBAR-0013-link-a-cloud-save-to-the-workflow-it-made.md b/docs/adr/SIDEBAR-0013-link-a-cloud-save-to-the-workflow-it-made.md new file mode 100644 index 000000000..e48ced7e2 --- /dev/null +++ b/docs/adr/SIDEBAR-0013-link-a-cloud-save-to-the-workflow-it-made.md @@ -0,0 +1,114 @@ +# ADR-SIDEBAR-0013: Link a Cloud Save to the Workflow It Made + +Date: 2026-11-09 + +## Status + +Accepted + +Accepted on 2026-11-10 by the author, after the 2026-11-09 design review chose +the workflow-id link. + +Relation: Refines [ADR-SIDEBAR-0009](SIDEBAR-0009-save-into-a-new-sidebar-folder-and-delete-only-the-record.md). +It changes one consequence of that record: the printed link opens its folder. +With a second Cloud flag on, the link opens the one saved workflow instead. +The feature-gated save, the new folder, the `overwrite=false` write, the +free-folder rule and the record-only delete stay as ADR-SIDEBAR-0009 says. + +## Context + +A person runs `comfy workflow save flux.json --name flux --where cloud`. The +CLI writes `workflows/flux/flux.json` and prints a link with `workflows=flux`. +Cloud's page opens every workflow file directly in that folder. If the person +later adds a second file there, the link opens both. If they move the file out, +the link opens nothing. + +Cloud copies each sidebar file into a workflow record named after its path: +`workflows/flux/flux.json` becomes the record `flux/flux` (ADR-SIDEBAR-0009 +lists this). The copy is best-effort, so a save can end with no record. The CLI +already searches for that record after the write to report `workflow_id`. + +Cloud's page can open a workflow by its record id. It reads the record, maps +the record's name back to its one sidebar path, checks that the file there +holds the record's newest version, and opens that file. Save in the browser +then writes back to the same file. When any check fails, the page does not +open the file. + +## Decision + +- Read `private_saved_file_links_enabled` from the same `GET /api/features` + reply as `cli_cloud_save_enabled`. Only a JSON `true` turns it on. It changes + only the link of a sidebar save. +- With it on, the link uses the record that the search after the write finds: + the live records named exactly `/`, every page read, with the + same page cap as the free-folder check. With exactly one such record, the + link is `?workspace=&workflowId=&deployment=`. + The workspace and deployment follow the folder link's rules: both go in only + when Cloud names the workspace. +- Otherwise the link stays the folder link. `data.url_opens` is `workflow` or + `folder`, or null with no link. For a folder link, `data.folder_link_reason` + is `workflow_links_off`, `record_not_found`, `record_ambiguous` or + `record_lookup_failed`. The last three also carry the existing + `workflow_record_unknown` warning. +- `workflow_id` keeps naming the record that `workflow get` and + `workflow delete` take. Record-only, API-format and local saves do not + change. + +## Alternatives considered + +- An id for the sidebar file itself, returned in Cloud's save reply. Rejected: + it needed a new Cloud route that reads files by id and a new field in the + save reply. Cloud already serves workflow records by id + (`GET /api/workflows/{workflow_id}`). +- Open the record's own content instead of the sidebar file. Rejected: Save in + the browser would not write back to the sidebar file, and a record that fell + behind its file would open old content. +- Keep only the folder link. Rejected: it opens other files added to the + folder, and it loses the file once the file moves. + +## What we reject + +- Picking one record when several live records share the name, or matching on + part of a name. +- Printing a `workflowId` link when the record search failed or ran past its + page cap. +- Changing the file write, the free-folder rule or delete to make the link + work. + +## Consequences + +### Positive + +- The link opens one workflow. A file added to the folder later does not open + with it. +- Cloud turns workflow links on or off for every installed CLI without a + release. Off restores the folder link. +- The save makes no new request. The record search it uses already ran to + report `workflow_id`. + +### Negative + +- When the file and its record drift apart, the link opens nothing: a record + that missed a rename, or a version added to the record and not the file. The + person opens the sidebar instead. +- The CLI cannot tell whether Cloud's page reads `workflowId`. The flag must + go on only once the page does. + +## Validation + +`tests/comfy_cli/command/test_workflow_saved.py` covers it in +`TestSaveLinksTheWorkflow`: one record gives a `workflowId` link, printed the +same in pretty output; a flag that is not a JSON `true` keeps the folder link; +zero records, two records, records +split across pages, a failed or unreadable search and a search past the page +cap each keep the folder link with their reason; deployment and an unknown +workspace follow the folder link's rules. `TestSaveFlagOffKeepsTheRecordSave` +keeps the record-only save when sidebar saving is off and workflow links are +on. + +## Revisit triggers + +- Cloud's page stops reading `workflowId`, or Cloud changes how a file becomes + a record. The flag goes off until the CLI matches. +- Cloud's save reply starts naming the record it made. Then the search after + the write can go. diff --git a/tests/comfy_cli/command/test_workflow_saved.py b/tests/comfy_cli/command/test_workflow_saved.py index 34512a184..ffd5eec84 100644 --- a/tests/comfy_cli/command/test_workflow_saved.py +++ b/tests/comfy_cli/command/test_workflow_saved.py @@ -775,6 +775,9 @@ def test_missing_file_surfaces_workflow_not_found(self, cloud_target, tmp_path, _FLAG_OFF = {"cli_cloud_save_enabled": False} _FLAG_ON = {"cli_cloud_save_enabled": True} +# Sidebar saving and workflow-id links both on. +_LINKS_ON = {"cli_cloud_save_enabled": True, "private_saved_file_links_enabled": True} +_WORKFLOW_UUID = "2c2fd5e2-c367-48cf-936f-c561f2414c19" # An editor-format workflow: the only kind the sidebar can open. _UI_DATA = {"nodes": [{"id": 1, "type": "KSampler", "widgets_values": [20]}], "links": [], "version": 0.4} # An API-format workflow: saved the record-only way even with the flag on. @@ -816,6 +819,7 @@ def _sidebar( records=(), workspace=_WORKSPACE, lookup_after_write=None, + ids=None, ): """A fake Cloud. @@ -823,9 +827,11 @@ def _sidebar( subfolder (listed only with ``recurse=true``), a POST into a ``conflict`` folder gets 409, and ``records`` are the names of live workflow records. A written file is mirrored into a record named after its path, as Cloud - does. ``lookup_after_write``, when set, answers the record search once a - file has been written. + does; ``ids`` maps a record name to its id (default ``rec-``). + ``lookup_after_write``, when set, answers the record search once a file + has been written; a callable gets the search's offset. """ + ids = ids or {} import urllib.parse state = {"records": list(records), "written": False} @@ -856,9 +862,15 @@ def handler(method, url, body): return {"path": key, "size": len(body), "modified": 1700000000000} if parsed.path == "/api/workflows" and method == "GET": if state["written"] and lookup_after_write is not None: + if callable(lookup_after_write): + return lookup_after_write(int(query["offset"][0])) return lookup_after_write needle = query["name"][0].lower() - rows = [{"id": f"rec-{n}", "name": n, "latest_version": 1} for n in state["records"] if needle in n.lower()] + rows = [ + {"id": ids.get(n, f"rec-{n}"), "name": n, "latest_version": 1} + for n in state["records"] + if needle in n.lower() + ] return {"data": rows, "pagination": {"total": len(rows), "limit": 100, "offset": 0}} if parsed.path == "/api/workflows" and method == "POST": return _RECORD_CREATED @@ -889,6 +901,8 @@ def test_writes_the_file_into_a_new_folder_and_prints_its_link(self, cloud_targe assert data["workspace_id"] == "ws_123" assert data["deployment"] == "standard" assert data["url"] == "https://cloud.example.com/?workspace=ws_123&workflows=flux&deployment=standard" + assert data["url_opens"] == "folder" + assert data["folder_link_reason"] == "workflow_links_off" assert "warnings" not in data (post,) = _posts(calls) assert post["url"] == "https://cloud.example.com/api/userdata/workflows%2Fflux%2Fflux.json?overwrite=false" @@ -1149,12 +1163,15 @@ def handler(method, url, body): assert env["ok"] is False assert len(_posts(calls)) == 1 - def test_api_format_keeps_the_record_save_with_a_warning(self, cloud_target, tmp_path, monkeypatch, capsys): + @pytest.mark.parametrize("features", [pytest.param(_FLAG_ON, id="sidebar"), pytest.param(_LINKS_ON, id="links")]) + def test_api_format_keeps_the_record_save_with_a_warning( + self, cloud_target, tmp_path, monkeypatch, capsys, features + ): # The sidebar opens a file as an editor graph, which builds nodes only # from nodes[]: an API-format file there would open empty. wf_path = tmp_path / "api.json" wf_path.write_text(json.dumps(_WF_DATA)) - calls = _patch_cloud(monkeypatch, _sidebar()) + calls = _patch_cloud(monkeypatch, _sidebar(features=features)) env = _run(["save", str(wf_path), "--name", "flux", "--where", "cloud"], capsys) assert env["ok"] is True assert env["data"]["workflow_id"] == "new-uuid" @@ -1166,6 +1183,208 @@ def test_api_format_keeps_the_record_save_with_a_warning(self, cloud_target, tmp assert not any("/api/userdata" in c["url"] for c in calls) +class TestSaveLinksTheWorkflow: + """With ``private_saved_file_links_enabled`` on, the link opens the one record Cloud made from the file.""" + + @pytest.fixture + def wf_path(self, tmp_path): + p = tmp_path / "wf.json" + p.write_text(json.dumps(_UI_DATA, indent=2)) + return p + + def _save(self, wf_path, capsys, *extra): + return _run(["save", str(wf_path), "--name", "flux", "--where", "cloud", *extra], capsys) + + @staticmethod + def _record_searches(calls): + return [c for c in calls if c["method"] == "GET" and "/api/workflows?name=flux%2Fflux&" in c["url"]] + + def test_one_record_gives_a_workflow_link(self, cloud_target, wf_path, monkeypatch, capsys): + calls = _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, ids={"flux/flux": _WORKFLOW_UUID})) + env = self._save(wf_path, capsys) + assert env["ok"] is True + data = env["data"] + assert data["url"] == ( + f"https://cloud.example.com/?workspace=ws_123&workflowId={_WORKFLOW_UUID}&deployment=standard" + ) + assert data["url_opens"] == "workflow" + assert data["folder_link_reason"] is None + # The link's id is the record id `workflow get` and `workflow delete` take. + assert data["workflow_id"] == _WORKFLOW_UUID + assert data["latest_version"] == 1 + assert data["filename"] == "workflows/flux/flux.json" + assert data["folder"] == "flux" + assert "warnings" not in data + # One features read decides both flags; the write is unchanged. + assert [c["url"] for c in calls].count("https://cloud.example.com/api/features") == 1 + (post,) = _posts(calls) + assert post["url"] == "https://cloud.example.com/api/userdata/workflows%2Fflux%2Fflux.json?overwrite=false" + assert post["body"] == wf_path.read_bytes() + # One search before the write (the free-folder check), one after it. + assert len(self._record_searches(calls)) == 2 + + def test_pretty_output_prints_the_same_workflow_link(self, cloud_target, wf_path, monkeypatch, capsys): + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, ids={"flux/flux": _WORKFLOW_UUID})) + json_url = self._save(wf_path, capsys)["data"]["url"] + assert f"workflowId={_WORKFLOW_UUID}" in json_url + + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, ids={"flux/flux": _WORKFLOW_UUID})) + r = Renderer.resolve( + is_stdout_tty=True, + env={}, + caller=Caller(kind="user", agentic=False, source_env=None), + json_flag=False, + ) + r.mode = OutputMode.PRETTY + set_renderer(r) + result = CliRunner().invoke( + workflow_cmd.app, ["save", str(wf_path), "--name", "flux", "--where", "cloud"], standalone_mode=False + ) + assert result.exception is None + out = capsys.readouterr().out + (result.stdout or "") + # Rich may wrap the long URL; compare with whitespace removed. + assert f"openit:{json_url}" in "".join(out.split()) + + def test_a_numbered_folder_links_its_own_record(self, cloud_target, wf_path, monkeypatch, capsys): + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, taken={"flux"}, ids={"flux (2)/flux": _WORKFLOW_UUID})) + env = self._save(wf_path, capsys) + assert env["data"]["folder"] == "flux (2)" + assert env["data"]["url_opens"] == "workflow" + assert f"workflowId={_WORKFLOW_UUID}" in env["data"]["url"] + assert "workflows=" not in env["data"]["url"] + + def test_the_deployment_goes_into_the_workflow_link(self, cloud_target, wf_path, monkeypatch, capsys): + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, ids={"flux/flux": _WORKFLOW_UUID})) + env = self._save(wf_path, capsys, "--deployment", "dep_9") + assert env["data"]["url"] == ( + f"https://cloud.example.com/?workspace=ws_123&workflowId={_WORKFLOW_UUID}&deployment=dep_9" + ) + + def test_an_unknown_workspace_leaves_it_out_of_the_workflow_link(self, cloud_target, wf_path, monkeypatch, capsys): + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, workspace={}, ids={"flux/flux": _WORKFLOW_UUID})) + env = self._save(wf_path, capsys) + assert env["data"]["url"] == f"https://cloud.example.com/?workflowId={_WORKFLOW_UUID}" + (warning,) = env["data"]["warnings"] + assert warning["code"] == "workspace_unknown" + assert "opens the workflow in" in warning["message"] + + @pytest.mark.parametrize( + "features", + [ + pytest.param(_FLAG_ON, id="missing"), + pytest.param({**_LINKS_ON, "private_saved_file_links_enabled": False}, id="off"), + pytest.param({**_LINKS_ON, "private_saved_file_links_enabled": "true"}, id="string"), + pytest.param({**_LINKS_ON, "private_saved_file_links_enabled": 1}, id="number"), + pytest.param({**_LINKS_ON, "private_saved_file_links_enabled": None}, id="null"), + ], + ) + def test_links_flag_not_true_keeps_the_folder_link(self, cloud_target, wf_path, monkeypatch, capsys, features): + _patch_cloud(monkeypatch, _sidebar(features, ids={"flux/flux": _WORKFLOW_UUID})) + env = self._save(wf_path, capsys) + data = env["data"] + assert data["url"] == "https://cloud.example.com/?workspace=ws_123&workflows=flux&deployment=standard" + assert data["url_opens"] == "folder" + assert data["folder_link_reason"] == "workflow_links_off" + # The record is still found and reported as before. + assert data["workflow_id"] == _WORKFLOW_UUID + assert "warnings" not in data + + @pytest.mark.parametrize( + ("lookup", "reason"), + [ + pytest.param({"data": []}, "record_not_found", id="zero"), + pytest.param( + {"data": [{"id": "x flux", "name": "x flux/flux"}, {"id": "Flux", "name": "Flux/Flux"}]}, + "record_not_found", + id="only-near-names", + ), + pytest.param( + {"data": [{"id": "a", "name": "flux/flux"}, {"id": "b", "name": "flux/flux"}]}, + "record_ambiguous", + id="two", + ), + pytest.param(_http_error(500), "record_lookup_failed", id="http-500"), + pytest.param(urllib.error.URLError("down"), "record_lookup_failed", id="unreachable"), + pytest.param(http.client.IncompleteRead(b"{"), "record_lookup_failed", id="truncated"), + pytest.param((b"", 200), "record_lookup_failed", id="unparseable"), + pytest.param({"rows": []}, "record_lookup_failed", id="no-data"), + pytest.param({"data": [{"name": "flux/flux"}]}, "record_lookup_failed", id="no-id"), + pytest.param({"data": [{"id": 7, "name": "flux/flux"}]}, "record_lookup_failed", id="number-id"), + ], + ) + def test_no_single_record_keeps_the_folder_link_and_says_why( + self, cloud_target, wf_path, monkeypatch, capsys, lookup, reason + ): + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, lookup_after_write=lookup)) + env = self._save(wf_path, capsys) + assert env["ok"] is True + data = env["data"] + assert data["url"] == "https://cloud.example.com/?workspace=ws_123&workflows=flux&deployment=standard" + assert data["url_opens"] == "folder" + assert data["folder_link_reason"] == reason + assert data["workflow_id"] is None + assert data["latest_version"] is None + (warning,) = data["warnings"] + assert warning["code"] == "workflow_record_unknown" + assert "the link opens the folder" in warning["message"] + + def test_a_record_on_the_second_page_is_found(self, cloud_target, wf_path, monkeypatch, capsys): + # The name search is a substring match: a full first page of longer + # names does not end it, and the record can sit on the next page. + full_page = { + "data": [{"id": f"r{i}", "name": f"x flux/flux {i}"} for i in range(100)], + "pagination": {"total": 101, "limit": 100, "offset": 0, "has_more": True}, + } + second = { + "data": [{"id": _WORKFLOW_UUID, "name": "flux/flux", "latest_version": 1}], + "pagination": {"total": 101, "limit": 100, "offset": 100, "has_more": False}, + } + pages = {0: full_page, 100: second} + calls = _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, lookup_after_write=pages.__getitem__)) + env = self._save(wf_path, capsys) + assert env["data"]["url_opens"] == "workflow" + assert env["data"]["workflow_id"] == _WORKFLOW_UUID + assert f"workflowId={_WORKFLOW_UUID}" in env["data"]["url"] + offsets = [c["url"].rsplit("offset=", 1)[1].split("&", 1)[0] for c in self._record_searches(calls)] + assert offsets == ["0", "0", "100"] + + def test_two_records_split_across_pages_are_ambiguous(self, cloud_target, wf_path, monkeypatch, capsys): + first = { + "data": [{"id": "a", "name": "flux/flux"}] + + [{"id": f"r{i}", "name": f"x flux/flux {i}"} for i in range(99)], + "pagination": {"total": 101, "limit": 100, "offset": 0, "has_more": True}, + } + second = { + "data": [{"id": "b", "name": "flux/flux"}], + "pagination": {"total": 101, "limit": 100, "offset": 100, "has_more": False}, + } + pages = {0: first, 100: second} + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, lookup_after_write=pages.__getitem__)) + env = self._save(wf_path, capsys) + assert env["data"]["url_opens"] == "folder" + assert env["data"]["folder_link_reason"] == "record_ambiguous" + + def test_a_search_past_the_page_cap_keeps_the_folder_link(self, cloud_target, wf_path, monkeypatch, capsys): + def every_page_full(offset): + return { + "data": [{"id": f"r{offset + i}", "name": f"x flux/flux {offset + i}"} for i in range(100)], + "pagination": {"has_more": True}, + } + + calls = _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, lookup_after_write=every_page_full)) + env = self._save(wf_path, capsys) + assert env["data"]["url_opens"] == "folder" + assert env["data"]["folder_link_reason"] == "record_lookup_failed" + # One search before the write, then the page cap after it. + assert len(self._record_searches(calls)) == 1 + workflow_cmd._MAX_RECORD_PAGES + + def test_more_to_come_with_no_rows_keeps_the_folder_link(self, cloud_target, wf_path, monkeypatch, capsys): + empty = {"data": [], "pagination": {"total": 5, "limit": 100, "offset": 0, "has_more": True}} + _patch_cloud(monkeypatch, _sidebar(_LINKS_ON, lookup_after_write=empty)) + env = self._save(wf_path, capsys) + assert env["data"]["folder_link_reason"] == "record_lookup_failed" + + class TestSaveFlagOffKeepsTheRecordSave: """Flag off, missing, or unreadable: the save is the record-only POST, as before the flag.""" @@ -1173,6 +1392,7 @@ class TestSaveFlagOffKeepsTheRecordSave: "features", [ pytest.param(_FLAG_OFF, id="off"), + pytest.param({**_LINKS_ON, "cli_cloud_save_enabled": False}, id="off-with-links-on"), pytest.param({}, id="missing"), pytest.param({"cli_cloud_save_enabled": "true"}, id="not-a-bool"), pytest.param([], id="not-an-object"), diff --git a/tests/comfy_cli/skills/test_installer.py b/tests/comfy_cli/skills/test_installer.py index a2f779463..4d86c86c7 100644 --- a/tests/comfy_cli/skills/test_installer.py +++ b/tests/comfy_cli/skills/test_installer.py @@ -616,6 +616,36 @@ def test_run_on_cloud_skill_drops_the_later_milestone_links(): assert gone not in text, f"comfy-run-on-cloud skill should not mention {gone}" +def test_run_on_cloud_skill_explains_workflow_and_folder_links(): + """The save's link opens the one workflow or its folder; the skill hands + back `data.url` as it is and reads why a folder link was given.""" + text = " ".join(skill_content("comfy-run-on-cloud").split()) + for needle in ( + "Hand back `data.url` as returned", + "`data.url_opens`", + "workflowId=", + "workflows=", + "`data.folder_link_reason`", + "`workflow_links_off`", + "`record_not_found`", + "`record_ambiguous`", + "`record_lookup_failed`", + "`workflow_record_unknown`", + "Cloud checks the link against the saved file when it opens", + "not listed here as `folder`", + "`data.filename`", + ): + assert needle in text, f"comfy-run-on-cloud skill should mention {needle}" + # The Cloud page is not part of this repository; the skill does not quote it. + assert "Couldn't open this workflow" not in text + + +def test_comfy_skill_reads_an_unknown_link_value_as_folder(): + text = " ".join(skill_content("comfy").split()) + assert "`data.url_opens`" in text + assert "treat a value not listed here as `folder`" in text + + def test_run_on_cloud_skill_asks_before_every_upload_and_lossy_swap(): text = " ".join(skill_content("comfy-run-on-cloud").split()) assert "uploading any file from this machine" in text