Skip to content
15 changes: 15 additions & 0 deletions comfy_cli/skills/comfy/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,21 @@ comfy --json workflow apply wf.json --ops ops.json $CAT # or --ops - to read s
# → data.ops[] (all minted ids), data.aliases{ckpt,ks}. Atomic: nothing writes if any spec fails.
```

**Adding, removing or reordering DynamicGroup rows** (e.g. a LoRA stack's `loras`):
send the desired row list in one `set_dynamic_group_rows` spec instead of
editing the count and numbered fields separately. Omitted fields take the template
default (a combo without one takes its first option, so name the LoRA explicitly; a field with no default at all must be supplied); a seed field's control mode is
`"<field>.0"` in the row. A row with a connected or promoted field keeps its index and
values; leave it out of `rows`, which fill the other positions in order, so the batch
fails if that row would have to move. Do not write the same group elsewhere in the batch.
Links are checked when the workflow is read: a link added to a row after that read is
not rechecked, so the spec can rewrite that row under its link.

```json
{"op":"set_dynamic_group_rows","node":12,"group":"loras",
"rows":[{"lora_name":"style.safetensors","strength":0.8},{"lora_name":"detail.safetensors"}]}
```

**Reusable recipes (the reuse path — prefer this over fragments/compose).** A recipe
is an ops file with a `params` header and `${param}` holes:

Expand Down
170 changes: 170 additions & 0 deletions comfy_cli/workflow_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,149 @@ def set_widget(
raise _enrich_resolution_error(e, workflow, graph, widget=widget) from e


def set_dynamic_group_rows(
workflow: dict,
graph,
node_id: Any,
group: str,
rows: Any,
*,
actor: str = "cli",
base_version: int = 0,
) -> tuple[dict, list[dict]]:
"""Replace a DynamicGroup's rows with ``rows``, expressed as ordinary
``set_widget`` ops: the row count first, then every widget of each written
row, including a field's ``<field>.0`` control mode. Omitted widgets take
the template default.

A row with a connected or promoted field keeps its index and values and
is left out of ``rows``, which fill the other positions in order. Links
are never moved, so ``rows`` must cover every free position before the
last pinned row.

The writes run on a copy, so ``workflow`` is unchanged when any is refused.
The ops share one stamp, so an earlier write to the group at the same
stamp is refused rather than left to the ``op_id`` tiebreak (revisit once
#1007 makes the later write in a batch win). ``apply_op`` must replay them
in order, because this workflow model materializes rows from the count.
"""
from comfy_cli.cql import engine as _engine
from comfy_cli.cql import promoted as _promoted

workflow = copy.deepcopy(workflow)
node_id = _template_id(workflow, node_id, graph)
target = _resolve_widget_write(workflow, graph, node_id, group)
Comment thread
jaeone94 marked this conversation as resolved.
Resolved
if target.kind == "top" and target.redirected_from is None:
node = target.node
segments = [str(node.get("id"))]
elif target.kind == "interior" and target.redirected_from is None:
node = _promoted._navigate(workflow, target.segments, _promoted.defs_by_id(workflow))
segments = target.segments
else:
raise ValueError(
f"{group}: replace rows on the node that owns the DynamicGroup, not a promoted or linked address"
)
m = graph.node(node.get("type", ""))
port = next((p for p in m.inputs if p.name == group and p.is_dynamic_group), None) if m else None
if port is None:
raise ValueError(f"{group!r} is not a DynamicGroup on node {node_id}")
if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows):
raise ValueError(f"{group}: rows must be a list of objects keyed by row field")
widgets = _engine._dynamic_group_widgets(port)
names = [widget.name for widget in widgets]
for i, row in enumerate(rows):
unknown = [key for key in row if key not in names]
if unknown:
raise ValueError(f"{group}: rows[{i}] has unknown field(s) {unknown}; row fields: {', '.join(names)}")
for widget in widgets:
if widget.name not in row and _engine._widget_default(widget) is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low — _widget_default falls back to the first enum option for a COMBO with no declared default, so lora_name is effectively never required. A row like {"strength": 0.8} silently picks whichever LoRA the server lists first, although SKILL.md and this error text say a field with no default must be supplied. The test only passes because its combo has options: []. Check the declared default for combo fields here, or document that a combo's first option is used.

Raised by 1 of 6 reviewers (claude-opus-5-5-xhigh edge-case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented in SKILL.md: a combo without a declared default takes its first option, so the agent should name the LoRA explicitly. The "no default" refusal covers only fields with no default at all. Using the first option is how the frontend fills a new row, so replacement keeps that default instead of adding a stricter one.

raise ValueError(f"{group}: field {widget.name!r} has no default; supply it in rows[{i}]")

entries = _engine._validate_dynamic_group_layout(node, m) or []
current = sum(1 for e in entries if e.owner == group) // len(widgets)
Comment thread
jaeone94 marked this conversation as resolved.
Resolved
linked = set()
for inp in node.get("inputs") or []:
if isinstance(inp, dict) and inp.get("link") is not None:
Comment thread
jaeone94 marked this conversation as resolved.
Resolved
widget = inp.get("widget")
linked.update(
name
for name in (inp.get("name"), widget.get("name") if isinstance(widget, dict) else None)
if isinstance(name, str)
)
fields = [field.name for field in _engine._dynamic_group_fields(port)]

def pin_reason(row: int) -> str | None:
# A link, or a promotion whose write lands on the host (a subgraph
# input or a legacy proxyWidgets entry), owns the row's value.
for name in fields:
address = f"{group}.{row}.{name}"
try:
target = _promoted.resolve_write(workflow, graph, segments, address)
except ValueError: # fed by another interior node: a plain link
target = None
if target is not None and (target.redirected_from or target.kind not in ("top", "interior")):
return "is promoted to the parent subgraph; unpromote it first"
if address in linked:
Comment thread
jaeone94 marked this conversation as resolved.
Resolved
return "is connected; disconnect it first"
return None

pinned = {r: reason for r in range(current) if (reason := pin_reason(r))}
Comment thread
jaeone94 marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low — The round-3 reply showed that a stale legacy proxyWidgets entry does not redirect. A stale live link on a row at index >= current is a different case that the reply doesn't cover. pinned only scans range(current), so when the replacement regrows the group past that index, the row writes land on a field whose input still carries a link, and the link silently overrides the supplied value at run time. One way to get there: _write_dynamic_group_count matches removed-row inputs by inp["name"], so an input linked by widget name only (the shape used in this PR's pins_a_row_connected_by_widget_name_only test) survives a scalar set_widget loras 1 shrink with its link intact. Check linked against every index in range(len(plan)), and refuse (or pin) any recreated row that has a live link.

Raised by 3 of 6 reviewers (gpt-5.6-sol-xhigh adversarial, kimi-k3-high adversarial, kimi-k3-high edge-case).

↩︎ re-raise of #1004 (comment) (round 3)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1a2969f. This is reproducible when the input does not shift: an input linked by widget.name only survives a scalar shrink. Before writing, rows from current up to the new length are checked against the linked names, and a match is refused with <group>.<N> still has a link from an earlier row; disconnect it first. Test: test_group_row_replacement_refuses_a_recreated_row_that_still_has_a_link.

last = max(pinned, default=None)
free_before_last = last + 1 - len(pinned) if pinned else 0
if len(rows) < free_before_last:
raise ValueError(
f"{group}.{last} keeps its position and is left out of rows; supply at least "
f"{free_before_last} row(s), or {group}.{last} {pinned[last]}"
)
maximum = port.options.max if port.options.max is not None else 20
if len(rows) + len(pinned) > maximum:
raise ValueError(
f"{group}: {len(rows)} row(s) plus {len(pinned)} connected or promoted row(s) exceed the maximum of {maximum}"
)
supplied = iter(rows)
plan = [None if index in pinned else next(supplied) for index in range(len(rows) + len(pinned))]
Comment thread
jaeone94 marked this conversation as resolved.
Resolved
for index in range(current, len(plan)):
# A shrink can leave a link on an input it did not match by name.
if any(f"{group}.{index}.{name}" in linked for name in fields):
raise ValueError(f"{group}.{index} still has a link from an earlier row; disconnect it first")
address = "/".join(segments) if len(segments) > 1 else node_id
where = segments if len(segments) > 1 else str(node_id)
stamps = workflow.get("_widget_stamps") or {}
claimed = [group] + [
f"{group}.{i}.{w.name}"
for i in range(max(len(plan), current))
if i >= len(plan) or plan[i] is not None
for w in widgets
]
for written in claimed:
prior = stamps.get(json.dumps(["widget", where, written]))
if prior is not None and list(prior[:2]) >= [base_version, actor]:
raise ValueError(
f"{group}: {written} is already written at stamp [{prior[0]}, {prior[1]}]; write the group once "
f"per batch (a stamp left by an earlier apply needs a higher base_version)"
)

# The address is resolved, so skip set_widget's retry on another node.
workflow, op = _set_widget_impl(workflow, graph, address, group, len(plan), actor=actor, base_version=base_version)
ops = [op]
for index, row in enumerate(plan):
if row is None:
continue
for widget in widgets:
value = row[widget.name] if widget.name in row else _engine._widget_default(widget)
workflow, op = _set_widget_impl(
workflow,
graph,
address,
f"{group}.{index}.{widget.name}",
value,
actor=actor,
base_version=base_version,
)
ops.append(op)
return workflow, ops


def _inserted_node_id(workflow: dict, node_id: Any) -> str | None:
"""The top-level ``insert:<op>:root:node:<id>`` node a bare template id means.

Expand Down Expand Up @@ -2752,6 +2895,7 @@ def apply_specs(
pre_batch_hint = _available_nodes_hint(workflow)
aliases: dict[str, Any] = {}
ops: list[dict] = []
replaced: dict[tuple, bool] = {}
input_targets: set[str] = set()
try:
for i, spec in enumerate(specs):
Expand Down Expand Up @@ -2815,6 +2959,19 @@ def apply_specs(
actor=actor,
base_version=base_version,
)
elif kind == "set_dynamic_group_rows":
workflow, row_ops = set_dynamic_group_rows(
workflow,
graph,
resolve_ref(spec["node"], aliases),
spec["group"],
spec["rows"],
actor=actor,
base_version=base_version,
)
ops.extend(row_ops)
replaced.update({_write_target(row_op): row_op is row_ops[0] for row_op in row_ops})
continue
elif kind == "set_node_field":
workflow, op = set_node_field(
workflow,
Expand All @@ -2837,6 +2994,19 @@ def apply_specs(
raise ValueError(f"spec #{i}: unknown op {kind!r}")
except KeyError as e:
raise ValueError(f"spec #{i} ({kind}) is missing required field {e}") from e
# A later write at the batch's stamp would tie with the replacement
# and be settled by the random op_id. Revisit once #1007 makes the
# later write in a batch win.
target = _write_target(op) if op.get("op") == "set_widget" else None
if target in replaced:
raise ValueError(
f"spec #{i}: {target[2]} was replaced earlier in this batch by set_dynamic_group_rows; "
Comment thread
jaeone94 marked this conversation as resolved.
Resolved
+ (
"change the number of rows in that spec instead"
if replaced[target]
else "put the value in its rows instead"
)
)
if kind in {"connect", "disconnect"}:
grow = op.get("grow")
if grow is not None and not grow.get("promoted"):
Expand Down
9 changes: 9 additions & 0 deletions docs/op-vocabulary-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ atomically with its own registered error code —
`workflow_clear_not_batchable` / `workflow_reset_doc_not_batchable` — and a hint
naming the standalone command. Nothing from such a batch is applied.

`set_dynamic_group_rows` is a batch spec, not an op kind. It replaces a
DynamicGroup's rows (`{"op": "set_dynamic_group_rows", "node": ..., "group":
"loras", "rows": [{...}]}`) and emits only `set_widget` ops: the row count, then
every widget of each written row, including a field's `<field>.0` control mode.
Rows with a connected or promoted field keep their index, are not rewritten, and
are left out of `rows`. comfy-cli's `apply_op` replays these in order because its
workflow model materializes rows from the count; the shared document accepts them
in any order. An earlier write to the group in the same batch is refused.

Every op carries the common envelope stamped by `_new_op`:

```json
Expand Down
Loading
Loading