diff --git a/catalog.json b/catalog.json index 3083392..06c2e4f 100644 --- a/catalog.json +++ b/catalog.json @@ -32,7 +32,7 @@ "fr": "Lire et modifier la scène ouverte dans Blender grâce à l'extension OpenCode Link : changements typés en un pas d'annulation, inspection du Blender lancé, rendus de vérification et en arrière-plan." }, "app": { "name": "Blender", "versions": ">=5.3" }, - "host": { "protocol": 1, "range": "^0.4.4" }, + "host": { "protocol": 1, "range": "^0.4.5" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/blender/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/blender/plugin"] } diff --git a/integrations/blender/host/opencode_link/addon.py b/integrations/blender/host/opencode_link/addon.py index 7310c9d..2005415 100644 --- a/integrations/blender/host/opencode_link/addon.py +++ b/integrations/blender/host/opencode_link/addon.py @@ -252,9 +252,9 @@ def _on_change(*_args): @persistent -def _on_save(*_args): +def _on_save(*args): if _session is not None: - _session.app.saved() + _session.app.saved(args[0] if args and isinstance(args[0], str) else None) @persistent diff --git a/integrations/blender/host/opencode_link/blender_app.py b/integrations/blender/host/opencode_link/blender_app.py index 1568ac4..96c43f8 100644 --- a/integrations/blender/host/opencode_link/blender_app.py +++ b/integrations/blender/host/opencode_link/blender_app.py @@ -165,7 +165,10 @@ def __init__(self, code_execution_allowed): self._revision = process_state().__dict__.pop("revision", 0) self._evaluations = 0 self._saves = 0 + self._loads = 0 self._saved_revision = None # the revision at the last save or load of a file + self._steps_since_save = [] # the OpenCode undo steps pushed since then + self._saved_content = None self._handle = new_script_handle() self._main = threading.main_thread() self.background = bool(bpy.app.background) @@ -233,12 +236,42 @@ def refresh_document(self): def document_known(self): return self._document_known - def saved(self): - """save_post handler: the document's file name may have changed.""" + def saved(self, path=None): + """save_post handler: the document's file name may have changed. Blender calls it for a copy too (with + the copy's path): the open file then keeps its changes.""" + current = getattr(bpy.data, "filepath", "") + if path and current and os.path.normcase(os.path.abspath(path)) != os.path.normcase(os.path.abspath(current)): + return self._saves += 1 self._saved_revision = self._revision + self._steps_since_save = [] + # Saved by an OpenCode run (a code run calling save_mainfile): what the file holds, to tell at the run's + # end whether the run changed anything after saving (settle_save). + self._saved_content = self.content_digest() if self._quiet else None self.refresh_document() + def settle_save(self): + """After a run that saved the open file and moved the revision: the document is as saved when its content + is the one saved. Blender's is_dirty says so only at the next event loop in an interface Blender.""" + saved, self._saved_content = self._saved_content, None + if saved is not None and self.content_digest() == saved: + self._saved_revision = self._revision + + def unsaved(self): + """What the file lacks, when the document differs from it: the file's name (None: never saved) and the + OpenCode steps since its last save or load. Changes made by hand are not listed.""" + if not self.unsaved_changes(): + return None + out = {"file": self._read_document()} + if out["file"] is None: + out["never_saved"] = True + steps = self._steps_since_save + if steps: + out["opencode_steps"] = steps[-10:] + if len(steps) > 10: + out["opencode_steps_count"] = len(steps) + return out + def refresh_display(self): from .handlers.captures import refresh_display @@ -323,17 +356,24 @@ def loaded(self): self.reset_native() self.refresh_document() self._revision += 1 + self._loads += 1 self._saved_revision = self._revision if bpy.data.filepath else None + self._steps_since_save = [] + + def loads(self): + """Documents loaded in this session (a code run that opened a file pushes no step into it).""" + return self._loads def unsaved_changes(self): - """Whether the document differs from its file. Blender's is_dirty, except in background mode, where it - stays set after any undo step even across a save and a reload: there, a document unchanged since its - last save or load counts as saved.""" + """Whether the document differs from its file. A document unchanged since its last save or load counts as + saved: Blender's is_dirty lags there (an interface Blender clears it only at its next event loop, after the + code run that saved; a background one keeps it after any undo step, even across a save and a reload). + Otherwise Blender's is_dirty.""" if not bpy.data.filepath: return True - if not bpy.data.is_dirty: + if self._saved_revision == self._revision: return False - return not (bpy.app.background and self._saved_revision == self._revision) + return bool(bpy.data.is_dirty) @contextlib.contextmanager def quiet(self): @@ -416,6 +456,9 @@ def _with_window(self, fn): def undo_push(self, message): self._with_window(lambda: bpy.ops.ed.undo_push(message=message[:63])) op_watch.undo_stack_made() + # A barrier marks a start; a failure step is undone at once by the restoration: neither is a change. + if not message.startswith(("OpenCode: before ", "OpenCode: failed ")): + self._steps_since_save = (self._steps_since_save + [message[:63]])[-50:] def undo(self): epoch = self.script_epoch() diff --git a/integrations/blender/host/opencode_link/blender_manifest.toml b/integrations/blender/host/opencode_link/blender_manifest.toml index b6e0215..863f2f4 100644 --- a/integrations/blender/host/opencode_link/blender_manifest.toml +++ b/integrations/blender/host/opencode_link/blender_manifest.toml @@ -1,7 +1,7 @@ schema_version = "1.0.0" id = "opencode_link" -version = "0.4.4" +version = "0.4.5" name = "OpenCode Link" tagline = "Lets OpenCode work on this Blender session" maintainer = "NeuralNomads" diff --git a/integrations/blender/host/opencode_link/core.py b/integrations/blender/host/opencode_link/core.py index ab2bfad..e222381 100644 --- a/integrations/blender/host/opencode_link/core.py +++ b/integrations/blender/host/opencode_link/core.py @@ -372,6 +372,9 @@ def _state(self): state["quarantined"] = True if self.quarantine: state["quarantine"] = self.quarantine + unsaved = self.app.unsaved() if hasattr(self.app, "unsaved") else None + if unsaved: + state["unsaved"] = unsaved # the file on disk lacks changes of the open document return state def _context(self, params): @@ -381,6 +384,9 @@ def _context(self, params): output = self.app.native_context(params["query"]) if self.quarantined: output["quarantined"] = True + unsaved = self.app.unsaved() if hasattr(self.app, "unsaved") else None + if unsaved: + output["unsaved"] = unsaved return output reads = params.get("reads", []) if not isinstance(reads, list) or len(reads) > MAX_READS: @@ -852,6 +858,7 @@ def _guarded(self, run, label, barrier): # depsgraph updates all, which say nothing. It changed the document only when its content differs after. content = self.app.content_digest() if not barrier and hasattr(self.app, "content_digest") else None saves = self.app.saves() if hasattr(self.app, "saves") else 0 + loads = self.app.loads() if hasattr(self.app, "loads") else 0 value = error = trace = restored = step = None with self.app.quiet(): if barrier: @@ -872,7 +879,11 @@ def _guarded(self, run, label, barrier): else: changed = self.app.evaluations() > evaluations or (digest is not None and self.app.change_digest() != digest) saved = (self.app.saves() if hasattr(self.app, "saves") else 0) > saves - if changed and barrier and error is None and not saved: + # The run opened another file: the barrier was the old document's; the new one is as loaded. + replaced = (self.app.loads() if hasattr(self.app, "loads") else 0) > loads + if replaced: + changed = True + elif changed and barrier and error is None and not saved: step = "OpenCode: %s" % label self.app.undo_push(step) elif changed and barrier and error is None: @@ -884,8 +895,10 @@ def _guarded(self, run, label, barrier): restored = before is not None and self._restore(before, label) if not restored: self._quarantine("failed %s: %s" % (label, error)) - if changed: - self.app.bump_revision() + if changed and not replaced: + self.app.bump_revision() # a load already moved the revision + if saved and hasattr(self.app, "settle_save"): + self.app.settle_save() # nothing changed after the save: the document is as saved return _Run(value=value, error=error, trace=trace, changed=changed, restored=restored, undo_step=step, stdout=out.getvalue(), stderr=err.getvalue(), revision_before=revision, saved=saved) @@ -910,6 +923,7 @@ def _execute_code(self, params): # modified: inspections and runs after a save leave the file saved; a change is reported, never undone. read_only = params.get("read_only") is True rotations = self.app.rotation_snapshot() if hasattr(self.app, "rotation_snapshot") else None + unsaved_before = self.app.unsaved() if hasattr(self.app, "unsaved") else None notes, hint = [], [] def run(): @@ -947,6 +961,9 @@ def finish(deferred=None, deferred_error=None): output["undo_step"] = done.undo_step if done.saved: output["saved"] = True + # What that save wrote of OpenCode's: the steps the file lacked before the run (none: an empty list). + output["saved_steps"] = (unsaved_before or {}).get("opencode_steps", []) + ( + ["OpenCode: code (this run)"] if done.changed else []) if warnings: output["warnings"] = warnings if done.error: diff --git a/integrations/blender/host/ops.json b/integrations/blender/host/ops.json index 6fb3854..82dc6bc 100644 --- a/integrations/blender/host/ops.json +++ b/integrations/blender/host/ops.json @@ -1,6 +1,6 @@ { "addon": "opencode_link", - "version": "0.4.4", + "version": "0.4.5", "protocol": 1, "method": "apply", "wire": "params.operations: [{op, args}] with every op below (an edit batch); unknown ops and fields are refused", diff --git a/integrations/blender/plugin/README.md b/integrations/blender/plugin/README.md index 443f0ce..9f2a87e 100644 --- a/integrations/blender/plugin/README.md +++ b/integrations/blender/plugin/README.md @@ -44,19 +44,19 @@ The **Plugins** section lists OpenCode for Blender as an integration: its versio ## Tools -| Tool | What it does | -| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `blender_hosts` | The offered Blenders (label, document, Blender version, whether this conversation or another one is attached to each) and the add-on's install state; `attach` attaches one (asks permission), `detach` releases this conversation's. | -| `blender_install_host` | Installs or updates OpenCode Link in the newest Blender 5.3 or later (asks permission). | -| `blender_context` | A compact read of the scene: revision, scene settings, collections, markers, a page of objects with their transforms; `ref` gives one object in detail (world bounds, pose bones); `include: ["parts"]` lists a mesh's loose parts (world box, material, dominant vertex group), `region` keeps those in a world box. | -| `blender_apply` | Up to 50 typed operations as one undo step, checked whole before anything changes; a failure part-way restores every changed field. See [Typed operations](#typed-operations). | -| `blender_execute_code` | Python in Blender; every run asks the `blender_execute_code` permission. See [Code execution](#code-execution). | -| `blender_lab` | One of Blender Lab's tools (object and file summaries, screenshots, views, thumbnails), run by the add-on; images come back as attachments. | -| `blender_inspect` | What this Blender really exposes: `search` (words found in its types, properties, functions and operators, with their paths and the properties that lead to a type), a type (properties, functions; a node type's real sockets, made in the `tree` named), an operator (parameters, the element type of its collections, its poll here with Blender's reason) or live data; entries beyond `limit` are named, `match` takes a glob or words. With the links to the API docs, manual and release notes of its version. | -| `blender_verify` | `criteria`: the agent's checks (a read-only expression or a `bpy.data` path, a comparison, a value, frames), each measured on the evaluated scene and passed or failed with the value; `visible`: whether an object shows in the render at a frame, otherwise every reason found (out of frame, hidden in render, collection excluded, view layer not rendered, holdout, transparent or zero-density material, no geometry, hidden behind another object). Without them, or with `render` or `view`: a low-resolution render of the scene's final output, or from a free viewpoint (`view`: location, target, lens), with facts: black or transparent, brightness, the camera used and why, strips, instances. `frames` returns several frames as one contact sheet; `scene` chooses the scene (the facts name the one read, and warn when it is a shot of a montage). Settings, cameras and frame are restored; the revision stays. | -| `blender_render` | A render in a separate background Blender to an exact output (an image, a frame pattern or an H.264 video, with the montage's sound when it has any; the result lists the streams written), followed as a task (`task`, `wait_s` up to an hour, `cancel`). It renders the saved file (`unsaved`). | -| `blender_save` | Saves the file, under a path, or a copy; a save that failed because another process held the file a moment is retried once and says so (`retried`). | -| `blender_import` | BlenderKit and Sketchfab searches, and imports from them or from a file (glTF, FBX, OBJ, USD; a path or an https URL), followed as a task (`task`, `wait_s`, `cancel`). BlenderKit and Sketchfab need their add-ons. | +| Tool | What it does | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `blender_hosts` | The offered Blenders (label, document, Blender version, whether this conversation or another one is attached to each) and the add-on's install state; `attach` attaches one (asks permission), `detach` releases this conversation's. | +| `blender_install_host` | Installs or updates OpenCode Link in the newest Blender 5.3 or later (asks permission). | +| `blender_context` | A compact read of the scene: revision, scene settings, collections, markers, a page of objects with their transforms; `ref` gives one object in detail (world bounds, pose bones); `include: ["parts"]` lists a mesh's loose parts (world box, material, dominant vertex group), `region` keeps those in a world box. | +| `blender_apply` | Up to 50 typed operations as one undo step, checked whole before anything changes; a failure part-way restores every changed field. See [Typed operations](#typed-operations). | +| `blender_execute_code` | Python in Blender; every run asks the `blender_execute_code` permission. See [Code execution](#code-execution). | +| `blender_lab` | One of Blender Lab's tools (object and file summaries, screenshots, views, thumbnails), run by the add-on; images come back as attachments. | +| `blender_inspect` | What this Blender really exposes: `search` (words found in its types, properties, functions and operators, with their paths and the properties that lead to a type), a type (properties, functions; a node type's real sockets, made in the `tree` named), an operator (parameters, the element type of its collections, its poll here with Blender's reason) or live data; entries beyond `limit` are named, `match` takes a glob or words. With the links to the API docs, manual and release notes of its version. | +| `blender_verify` | `criteria`: the agent's checks (a read-only expression or a `bpy.data` path, a comparison, a value, frames), each measured on the evaluated scene and passed or failed with the value; `visible`: whether an object shows in the render at a frame, otherwise every reason found (out of frame, hidden in render, collection excluded, view layer not rendered, holdout, transparent or zero-density material, no geometry, hidden behind another object). Without them, or with `render` or `view`: a low-resolution render of the scene's final output, or from a free viewpoint (`view`: location, target, lens), with facts: black or transparent, brightness, the camera used and why, strips, instances. `frames` returns several frames as one contact sheet; `scene` chooses the scene (the facts name the one read, and warn when it is a shot of a montage). `caches` names the simulation caches the checked frames read without a current bake (not baked, outdated, frames outside it) (Blender marks a rigid body bake outdated whenever its file is opened, and says so in `note`); `unsaved`, what the saved file lacks. Settings, cameras and frame are restored; the revision stays. | +| `blender_render` | A render in a separate background Blender to an exact output (an image, a frame pattern or an H.264 video, with the montage's sound when it has any; the result lists the streams written), followed as a task (`task`, `wait_s` up to an hour, `cancel`). It renders the saved file (`unsaved`). | +| `blender_save` | Saves the file, under a path, or a copy, and says what it wrote (bytes; `wrote_steps`, the OpenCode steps now in the file, an empty list when none was pending) and, after a copy, what the open file still lacks (`unsaved`); a save that failed because another process held the file a moment is retried once and says so (`retried`). | +| `blender_import` | BlenderKit and Sketchfab searches, and imports from them or from a file (glTF, FBX, OBJ, USD; a path or an https URL), followed as a task (`task`, `wait_s`, `cancel`). BlenderKit and Sketchfab need their add-ons. | `blender_inspect`, `blender_verify`, `blender_render` and `blender_save` send fixed programs of the package (`programs/*.py`) through the host's code execution, read only, with their parameters as JSON data; they ask no permission because they run no code from the model. Without `if_revision` and `command_id`, `blender_apply` applies to the document as it is now under a new `command_id`; with them it is refused when the scene changed, and a replayed `command_id` applies nothing. @@ -129,6 +129,8 @@ Add-on settings (Preferences ▸ Add-ons ▸ OpenCode Link): _OpenCode service_ `blender_execute_code` runs Python in Blender with your rights: it can read and write files, start processes and reach the network. The add-on lists it while it is enabled, and **every run asks the `blender_execute_code` permission** ("ask" unless you allow it in OpenCode's permission settings); a refused run executes nothing. A run that changes the scene is one undo step; a failing one is undone. Blender keeps linked data outside its undo (a linked library, the brush a sculpt or paint mode links): it is named in `restoration.kept_linked`, unused and not saved. When an undo cannot be proven, OpenCode Link is **quarantined**: reads, `blender_verify`, `blender_inspect` and `read_only` code still run, changes wait; `blender_context` shows `quarantine.may_have_changed`, and once you checked it, `blender_context` with `release_quarantine` (that read's revision) lifts it, as does Reset in the add-on's panel. A long script can be a file (`path`): it is read as written, with no escaping through a JSON or JavaScript string, and its tracebacks name the file. See [`SECURITY.md`](../../../SECURITY.md). +When the open document differs from its file, the results of `blender_context`, `blender_apply`, `blender_execute_code` and `blender_verify` carry `unsaved`: the file's name (`never_saved` for a new document) and the OpenCode steps since its last save or load (changes made by hand are not listed); saving a copy leaves it, a run that saves the open file and changes nothing after clears it, and a run that opens a file pushes no step into it. + A run that fails on Blender's API carries a `hint` read from that Blender before the run is undone: for an unknown attribute, the closest names and the type's properties; for an operator's arguments, its real signature (with the element type of its collections) and the closest names; for an invalid enumeration value, the closest items; for a missing key, the collection's keys (a node's sockets included); for an unknown node type, the closest types the tree creates, with their sockets; for a failed poll, Blender's reason and the context the code had. While a run executes, OpenCode Link prepares two calls Blender 5.3 closes on from a script, as Blender's interactive path prepares them, and says so in `warnings`: a mask stroke (`sculpt.brush_stroke` with the Mask brush or `brush_toggle='MASK'`) on a multiresolution object gets its mask layer first, and in a Blender without interface a sculpt-mode operator gets a first undo step when none was pushed yet. If the attached Blender closes, the next call says so with the crash report it wrote (`.crash.txt` in its temporary folder), instead of an unreachable host. ## Blender limits diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.4.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.5.zip similarity index 99% rename from integrations/blender/plugin/host/blender/opencode_link-0.4.4.zip rename to integrations/blender/plugin/host/blender/opencode_link-0.4.5.zip index 4a7a8d4..70d9a9a 100644 Binary files a/integrations/blender/plugin/host/blender/opencode_link-0.4.4.zip and b/integrations/blender/plugin/host/blender/opencode_link-0.4.5.zip differ diff --git a/integrations/blender/plugin/methods/tools/blender_context.json b/integrations/blender/plugin/methods/tools/blender_context.json index 4167025..3a2c663 100644 --- a/integrations/blender/plugin/methods/tools/blender_context.json +++ b/integrations/blender/plugin/methods/tools/blender_context.json @@ -1,7 +1,7 @@ { "name": "blender_context", "domain": "tools", - "description": "Compact read of the attached Blender scene: revision, scene settings, collections, markers, a page of objects (name, type, parent, collections, location, rotation with its mode, scale). ref = one object in detail (world bounds; pose bones with head, world direction, rotation); include parts lists a mesh's loose parts (vertices, world box, material, dominant vertex group), region keeps those meeting a world box. Call first; pass revision to blender_apply. quarantined: changes wait; quarantine.may_have_changed says what to check.", + "description": "Compact read of the attached Blender scene: revision, scene settings, collections, markers, a page of objects (name, type, parent, collections, location, rotation with its mode, scale). ref = one object in detail (world bounds; pose bones with head, world direction, rotation); include parts lists a mesh's loose parts (vertices, world box, material, dominant vertex group), region keeps those meeting a world box. Call first; pass revision to blender_apply. quarantined: changes wait; quarantine.may_have_changed says what to check. unsaved: the file on disk lacks changes of the open document (with the OpenCode steps since its last save).", "kind": "host-backed", "risk": "read", "args": { diff --git a/integrations/blender/plugin/methods/tools/blender_save.json b/integrations/blender/plugin/methods/tools/blender_save.json index 967e19c..026fff2 100644 --- a/integrations/blender/plugin/methods/tools/blender_save.json +++ b/integrations/blender/plugin/methods/tools/blender_save.json @@ -1,7 +1,7 @@ { "name": "blender_save", "domain": "tools", - "description": "Save the open file; with path, save it under that .blend (as the open file, or a copy with copy true). Relative paths are next to the current file; an existing other file needs overwrite.", + "description": "Save the open file; with path, save it under that .blend (as the open file, or a copy with copy true). Relative paths are next to the current file; an existing other file needs overwrite. Says what it wrote (bytes, wrote_steps: the OpenCode steps now in the file) and, after a copy, what the open file still lacks (unsaved).", "kind": "host-backed", "risk": "write", "args": { diff --git a/integrations/blender/plugin/methods/tools/blender_verify.json b/integrations/blender/plugin/methods/tools/blender_verify.json index b67bcfe..ab67b98 100644 --- a/integrations/blender/plugin/methods/tools/blender_verify.json +++ b/integrations/blender/plugin/methods/tools/blender_verify.json @@ -1,7 +1,7 @@ { "name": "blender_verify", "domain": "tools", - "description": "Check a result by measurement. criteria: your own acceptance checks, each measured on the evaluated scene at its frames and passed or failed with the measured value. visible: whether an object shows in the render at a frame, otherwise every reason found (out of frame, hidden in render, collection excluded, view layer not rendered, holdout, transparent or zero-density material, no geometry, hidden behind another object). Render (the default without criteria or visible, or with render or view): low-resolution frames with facts (black or transparent, brightness, the camera used and why, sequencer, compositing, instances). Settings, cameras and the current frame are restored; the revision stays.", + "description": "Check a result by measurement. criteria: your own acceptance checks, each measured on the evaluated scene at its frames and passed or failed with the measured value. visible: whether an object shows in the render at a frame, otherwise every reason found (out of frame, hidden in render, collection excluded, view layer not rendered, holdout, transparent or zero-density material, no geometry, hidden behind another object). Render (the default without criteria or visible, or with render or view): low-resolution frames with facts (black or transparent, brightness, the camera used and why, sequencer, compositing, instances). caches: simulation caches the checked frames read without a current bake (not baked, outdated, frames outside); unsaved: the file lacks changes you checked here. Settings, cameras and the current frame are restored; the revision stays.", "kind": "host-backed", "risk": "read", "args": { diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index 43facbd..b503940 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@neuralnomads/opencode-blender", - "version": "0.4.4", + "version": "0.4.5", "description": "OpenCode for Blender: lets OpenCode read and change an open Blender scene through an authenticated local host, with typed edits, inspection, verification renders and background renders.", "license": "MIT AND GPL-3.0-or-later", "type": "module", @@ -60,10 +60,10 @@ "host": { "app": "blender", "protocol": 1, - "range": "^0.4.4", + "range": "^0.4.5", "appVersions": ">=5.3", - "payload": "host/blender/opencode_link-0.4.4.zip", - "sha256": "4c22359a8e759ae1da003eef5213d3c90334096278260e1968a535b1cc1d4f3c" + "payload": "host/blender/opencode_link-0.4.5.zip", + "sha256": "82ca90eca45d454f0d1fe403c2c4dd4cffc1d3990e1bd6e374ab515314adfb73" } } } diff --git a/integrations/blender/plugin/programs/verify.py b/integrations/blender/plugin/programs/verify.py index 3659990..06be24b 100644 --- a/integrations/blender/plugin/programs/verify.py +++ b/integrations/blender/plugin/programs/verify.py @@ -8,6 +8,7 @@ # criteria: the agent's own checks (a read-only expression or a bpy.data path, a comparison, a value, frames), # each measured on the evaluated scene and passed or failed. visible: whether an object shows in the render at # a frame, with every reason found when it does not. With either, the render runs only when asked (render, view). +# caches: the simulation caches the checked frames read without a current bake (not baked, outdated, outside). # PARAMS is prepended by the plugin: {"scene"?, "frame"?, "frames"?, "view"?, "size"?, "criteria"?, "visible"?, # "render"?} import base64 @@ -594,6 +595,67 @@ def render_frames(): +def checked_frames(): + found = set(frames) if RENDER else set() + for c in CRITERIA: + found.update(criterion_frames(c)) + if VISIBLE: + spec = {"object": VISIBLE} if isinstance(VISIBLE, str) else VISIBLE + found.update(int(x) for x in spec.get("frames") or [spec.get("frame", frames[0])]) + return sorted(found) + + +def simulation_caches(checked): + """The simulation caches whose frames the checks read without a valid bake: not baked (a frame is right only + when Blender stepped to it from the start), baked but outdated (made before a later change), or baked without + the checked frames. A baked, current cache covering them is not listed.""" + out = [] + + def add(owner, baked, outdated, start, end, info=""): + outside = [f for f in checked if not start <= f <= end] + if baked and not outdated and not outside: + return + entry = {"cache": owner, "baked": bool(baked), "frames": [start, end]} + if baked and outdated: + entry["outdated"] = True + if outside: + entry["checked_frames_outside"] = outside + if info: + entry["info"] = info[:120] + out.append(entry) + + def point_cache(owner, pc): + if pc is not None: + add(owner, pc.is_baked, pc.is_outdated, pc.frame_start, pc.frame_end, pc.info) + + world = scene.rigidbody_world + if world is not None and world.enabled: + point_cache("rigid body world", world.point_cache) + if out and out[-1]["cache"] == "rigid body world" and out[-1].get("outdated"): + # Blender 5.3 flags every rigid body bake outdated when its file is opened; its frames still play. + out[-1]["note"] = "Blender also marks a rigid body bake outdated when its file is opened; its baked frames still play" + for obj in scene.objects: + for m in obj.modifiers: + if not m.show_render and not m.show_viewport: + continue + point_cache("%s: %s" % (obj.name, m.name), getattr(m, "point_cache", None)) + settings = getattr(m, "domain_settings", None) if getattr(m, "fluid_type", None) == "DOMAIN" else None + if settings is not None: + add("%s: %s" % (obj.name, m.name), settings.has_cache_baked_any, False, + settings.cache_frame_start, settings.cache_frame_end) + canvas = getattr(m, "canvas_settings", None) if getattr(m, "ui_type", None) == "CANVAS" else None + for surface in getattr(canvas, "canvas_surfaces", []) if canvas is not None else []: + point_cache("%s: %s %s" % (obj.name, m.name, surface.name), surface.point_cache) + for ps in obj.particle_systems: + if ps.settings is None or (ps.settings.type == "HAIR" and not ps.use_hair_dynamics): + continue # still hair: nothing simulated + point_cache("%s: particles %s" % (obj.name, ps.name), ps.point_cache) + return out[:20] + + +caches = simulation_caches(checked_frames()) +if caches: + checks["caches"] = caches image_b64 = render_frames() if RENDER else None if len(per_frame) > 1: summary["frames"] = per_frame diff --git a/integrations/blender/plugin/src/integration.ts b/integrations/blender/plugin/src/integration.ts index f5c912e..e968d81 100644 --- a/integrations/blender/plugin/src/integration.ts +++ b/integrations/blender/plugin/src/integration.ts @@ -171,6 +171,8 @@ export function createRegistry(marker: IntegrationMarker, options: BlenderOption // label: the attached offer's label when the ticket was taken (a permission prompt shows it). type Ticket = { authority: BindingAuthority; bound: HostBinding; label?: string } +// A fixed program's run: its result, with what the open document's file lacks and what a save wrote. +type ProgramRun = { result?: unknown; unsaved?: unknown; saved?: boolean; saved_steps?: string[] } type Hello = { script_handle: string; revision: number; host_version?: string; document?: unknown } export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) { @@ -408,21 +410,30 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) } // A fixed program through the host's code execution, read only (programs.ts). - const program = async (context: ToolContext, name: ProgramName, params: unknown, timeoutMs?: number) => { + const programRun = async (context: ToolContext, name: ProgramName, params: unknown, timeoutMs?: number) => { const out = (await callHost( context, "execute_code", { code: programCode(name, params), read_only: true }, timeoutMs, - )) as { - status?: string - result?: unknown - message?: string - traceback?: string - } + )) as ProgramRun & { status?: string; message?: string; traceback?: string } if (out.status === "failed") throw new Error(`blender_${name}: ${String(out.message ?? "")}\n${String(out.traceback ?? "").slice(-1200)}`) - return out.result + return out + } + const program = async (context: ToolContext, name: ProgramName, params: unknown, timeoutMs?: number) => + (await programRun(context, name, params, timeoutMs)).result + + // A save, and what it wrote: the OpenCode steps now in the file, and what the open document still lacks + // (a copy leaves the open file as it was). + const save = async (context: ToolContext, args: Record) => { + const out = await programRun(context, "save", args) + return { + ...(out.result as Record), + // A save of the open file always says what it wrote of OpenCode's (none: an empty list). + ...(out.saved ? { wrote_steps: out.saved_steps ?? [] } : {}), + ...(out.unsaved ? { unsaved: out.unsaved } : {}), + } } // Replays of a command_id without its revision answer the first result (the host replays its own). @@ -587,12 +598,11 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) }, async blender_verify(args, context) { - const { image_base64, ...rest } = (await program(context, "verify", args, VERIFY_TIMEOUT_MS)) as { - image_base64?: string - } & Record - // Criteria first: what passed and failed, measured, then the facts. + const run = await programRun(context, "verify", args, VERIFY_TIMEOUT_MS) + const { image_base64, ...rest } = run.result as { image_base64?: string } & Record + // Criteria first: what passed and failed, measured, then what the saved file lacks, then the facts. const { blender, facts, ...checks } = rest - const text = json({ blender, ...checks, facts }) + const text = json({ blender, ...checks, ...(run.unsaved ? { unsaved: run.unsaved } : {}), facts }) if (!image_base64) return text return [ { type: "text", text }, @@ -712,15 +722,14 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) async blender_save(args, context) { try { - return json(await program(context, "save", args)) + return json(await save(context, args)) } catch (error) { // Blender renames the file aside while saving; another process holding it a moment (a background render // reading it) fails that rename, and the save changed nothing: once more, a second later, and said. const message = error instanceof Error ? error.message : String(error) if (!TRANSIENT_SAVE.test(message)) throw error await new Promise((done) => setTimeout(done, SAVE_RETRY_MS)) - const saved = (await program(context, "save", args)) as Record - return json({ ...saved, retried: message.split("\n")[0]?.slice(0, 300) }) + return json({ ...(await save(context, args)), retried: message.split("\n")[0]?.slice(0, 300) }) } }, } diff --git a/integrations/blender/test/blender.test.ts b/integrations/blender/test/blender.test.ts index 5a6bbf0..c431018 100644 --- a/integrations/blender/test/blender.test.ts +++ b/integrations/blender/test/blender.test.ts @@ -18,6 +18,8 @@ const OPS042_TESTS = 10 const OPS043_TESTS = 3 // The tests of ops044_tests.py: the 0.4.3 exercises' findings (QA journal, Luna section). const OPS044_TESTS = 12 +// The tests of ops045_tests.py: the 0.4.4 exercises' findings (QA journal, Luna section). +const OPS045_TESTS = 8 const folder = join(import.meta.dirname, "blender") type Result = { passed: string[]; failed: Array<{ name: string; error: string; trace: string }> } @@ -290,6 +292,62 @@ describe("OpenCode Link in Blender (background)", { skip }, () => { } }) + it("passes the tests of the 0.4.4 exercises' findings (0.4.5)", async () => { + assert.equal((await hostScript("ops045_tests.py", (scratch) => [scratch], 400_000)).passed.length, OPS045_TESTS) + }) + + it("results say what the saved file lacks, blender_save what it wrote, blender_verify the stale caches (0.4.5)", async () => { + const { iso, plugin, stop, json } = await served() + try { + const code = async (text: string) => { + const out = json(await plugin.tool("blender_execute_code", { code: text })) + assert.equal(out.status, "executed", JSON.stringify(out).slice(0, 1200)) + return out + } + const built = await code( + "import bpy\nbpy.ops.mesh.primitive_cube_add(location=(0, 0, 3))\nbpy.context.object.name = 'Brick'\n" + + "bpy.ops.rigidbody.object_add()", + ) + assert.equal(built.unsaved.never_saved, true) + const file = join(iso.root, "ex06.blend") + const saved = json(await plugin.tool("blender_save", { path: file })) + assert.ok(saved.wrote_steps.includes("OpenCode: code"), JSON.stringify(saved)) + assert.equal(saved.unsaved, undefined) + // Luna 06: the cache is checked at the frames verified; never baked here. + const checks = { criteria: [{ expr: "world('Brick').z", op: "<", value: 3, frame: 40 }] } + const fresh = json(await plugin.tool("blender_verify", checks)) + assert.equal(fresh.unsaved, undefined) + assert.deepEqual( + fresh.caches.map((c: { cache: string; baked: boolean }) => [c.cache, c.baked]), + [["rigid body world", false]], + ) + // Baked, then a change: the bake is outdated, and the file lacks the change. + await code( + "import bpy\npc = bpy.context.scene.rigidbody_world.point_cache\npc.frame_end = 60\n" + + "with bpy.context.temp_override(scene=bpy.context.scene, point_cache=pc):\n bpy.ops.ptcache.bake(bake=True)", + ) + json(await plugin.tool("blender_save", {})) + const moved = await code("import bpy\nbpy.data.objects['Brick'].location.x = 2") + assert.deepEqual(moved.unsaved, { file: "ex06.blend", opencode_steps: ["OpenCode: code"] }) + assert.equal(json(await plugin.tool("blender_context")).unsaved.file, "ex06.blend") + const stale = json( + await plugin.tool("blender_verify", { criteria: [{ ...checks.criteria[0], frames: [40, 90] }] }), + ) + assert.equal(stale.unsaved.file, "ex06.blend") + assert.equal(stale.caches[0].outdated, true, JSON.stringify(stale.caches)) + assert.deepEqual(stale.caches[0].checked_frames_outside, [90]) + // A copy leaves the open file as it was. + const copy = json(await plugin.tool("blender_save", { path: join(iso.root, "copy.blend"), copy: true })) + assert.equal(copy.unsaved.file, "ex06.blend", JSON.stringify(copy)) + assert.equal(copy.wrote_steps, undefined) + // A save with nothing pending from OpenCode says so (the trial's second save of the library). + assert.deepEqual(json(await plugin.tool("blender_save", {})).wrote_steps, ["OpenCode: code"]) + assert.deepEqual(json(await plugin.tool("blender_save", {})).wrote_steps, []) + } finally { + await stop() + } + }) + it("passes the tests of the western film's v7 frictions (0.4.2)", async () => { assert.equal((await hostScript("ops042_tests.py", (scratch) => [scratch], 400_000)).passed.length, OPS042_TESTS) }) diff --git a/integrations/blender/test/blender/ops045_tests.py b/integrations/blender/test/blender/ops045_tests.py new file mode 100644 index 0000000..fdad5c7 --- /dev/null +++ b/integrations/blender/test/blender/ops045_tests.py @@ -0,0 +1,191 @@ +"""The 0.4.4 exercises' findings (QA journal, Luna section: ex06, ex09): the agent checked the open document and +concluded while the saved file lacked its last changes. Results now say when the file lacks changes, and what a +save wrote. Each test fails on the 0.4.4 add-on and passes on 0.4.5, in a private background Blender 5.3 (run by +blender.test.ts). Prints RESULT . +Usage: blender -b --factory-startup --python ops045_tests.py -- +""" + +import importlib +import json +import os +import sys +import traceback + +import addon_utils +import bpy + +MODULE = "bl_ext.user_default.opencode_link" +addon_utils.enable(MODULE, default_set=True, handle_error=None) +addon = importlib.import_module(MODULE + ".addon") +session = addon.session() +core, app = session.core, session.app +session.stop() +SCRATCH = sys.argv[sys.argv.index("--") + 1] + + +def relay(handler): + """The add-on's own handler, its session stopped here (Blender passes a save the path written, a copy's too).""" + + @bpy.app.handlers.persistent + def run(*args): + addon._session = session + try: + handler(*args) + finally: + addon._session = None + + return run + + +bpy.app.handlers.save_post.append(relay(addon._on_save)) +bpy.app.handlers.load_post.append(relay(addon._on_load)) + +results = {"passed": [], "failed": [], "host_version": core.version} +TESTS = [] + + +def test(fn): + TESTS.append(fn) + return fn + + +def check(condition, message): + if not condition: + raise AssertionError(message) + + +def empty(): + bpy.ops.wm.read_factory_settings(use_empty=True) + core.quarantined = False + core.quarantine = None + bpy.context.view_layer.update() + addon.pump(0.05) + + +def run_code(text, read_only=False): + params = {"script_handle": app.script_handle(), "code": text} + if read_only: + params["read_only"] = True + return core.handle("execute_code", params) + + +def scene(): + return core.handle("scene", {"script_handle": app.script_handle()}) + + +@test +def u_a_never_saved_document_says_so_with_the_steps_made(): + empty() + out = run_code("import bpy\nbpy.data.objects.new('Robot', None)") + check(out["status"] == "executed", "runs: %s" % out) + check(out.get("unsaved") == {"file": None, "never_saved": True, "opencode_steps": ["OpenCode: code"]}, + "the result says the file lacks it: %s" % out.get("unsaved")) + check(scene().get("unsaved", {}).get("never_saved") is True, "the context too") + + +@test +def u09_after_a_save_a_later_change_is_named_until_the_next_save(): + empty() + path = os.path.join(SCRATCH, "shot010.blend") + run_code("import bpy\nbpy.data.objects.new('Robot', None)") + saved = run_code("import bpy\nbpy.ops.wm.save_as_mainfile(filepath=%r)" % path) + check(saved.get("saved") is True and saved.get("saved_steps") == ["OpenCode: code"], "the save wrote: %s" % saved) + check("unsaved" not in saved and "unsaved" not in scene(), "nothing unsaved after it: %s" % saved.get("unsaved")) + # Luna 09: the pose changed after the save. + posed = run_code("import bpy\nbpy.data.objects['Robot'].rotation_euler.z = 1.2") + check(posed.get("unsaved") == {"file": "shot010.blend", "opencode_steps": ["OpenCode: code"]}, + "the file lacks the pose: %s" % posed.get("unsaved")) + check(scene().get("unsaved", {}).get("file") == "shot010.blend", "the context says it") + read = run_code("import bpy\nresult = {'z': bpy.data.objects['Robot'].rotation_euler.z}", read_only=True) + check(read.get("unsaved", {}).get("opencode_steps") == ["OpenCode: code"], "a read says it too") + + +@test +def u_a_copy_leaves_the_open_file_unsaved(): + empty() + path = os.path.join(SCRATCH, "shot.blend") + run_code("import bpy\nbpy.ops.wm.save_as_mainfile(filepath=%r)" % path) + run_code("import bpy\nbpy.data.objects.new('Lamp', None)") + copy = run_code("import bpy\nbpy.ops.wm.save_as_mainfile(filepath=%r, copy=True)" % os.path.join(SCRATCH, "copy.blend"), + read_only=True) + check(copy["status"] == "executed" and "saved" not in copy, "a copy is not a save of the open file: %s" % copy) + check(copy.get("unsaved", {}).get("file") == "shot.blend", "the open file still lacks the lamp: %s" % copy.get("unsaved")) + + +@test +def u_a_file_opened_by_code_is_as_saved_and_gets_no_step(): + empty() + path = os.path.join(SCRATCH, "opened.blend") + run_code("import bpy\nbpy.context.scene.collection.objects.link(bpy.data.objects.new('Crate', None))\n" + "bpy.ops.wm.save_as_mainfile(filepath=%r)" % path) + run_code("import bpy\nbpy.data.objects.new('Other', None)") + opened = run_code("import bpy\nbpy.ops.wm.open_mainfile(filepath=%r)" % path) + check(opened["status"] == "executed" and "undo_step" not in opened, "opened, no step pushed into it: %s" % opened) + check("unsaved" not in opened and "unsaved" not in scene(), "the file as saved: %s" % opened.get("unsaved")) + check("Crate" in bpy.data.objects and "Other" not in bpy.data.objects, "the saved content") + + +# -- the 0.4.5 trial (ex06 #16, ex09 #9-#16): saves inside a code run, failed runs, a reopened bake ----------------- +@test +def t_a_failed_run_restored_is_not_a_step_of_the_file(): + empty() + run_code("import bpy\nbpy.ops.wm.save_as_mainfile(filepath=%r)" % os.path.join(SCRATCH, "failed.blend")) + out = run_code("import bpy\nbpy.data.objects.new('Stray', None)\nraise RuntimeError('like the trial')") + check(out["status"] == "failed" and out.get("restored") is True, "failed and restored: %s" % out) + steps = (out.get("unsaved") or {}).get("opencode_steps", []) + check(not any("failed" in s for s in steps), "the restoration is no step of the file: %s" % steps) + + +@test +def t06_a_run_that_changes_then_saves_leaves_nothing_unsaved(): + empty() + run_code("import bpy\nbpy.ops.wm.save_as_mainfile(filepath=%r)" % os.path.join(SCRATCH, "ex06.blend")) + run_code("import bpy\nbpy.context.scene.collection.objects.link(bpy.data.objects.new('Ground', None))") + out = run_code("import bpy\ns = bpy.context.scene\ns.collection.objects.link(bpy.data.objects.new('Brick', None))\n" + "s.frame_end = 120\ns.frame_set(120)\nbpy.ops.wm.save_as_mainfile(filepath=bpy.data.filepath)") + check(out["status"] == "executed" and out.get("saved") is True, "saved: %s" % out) + check("unsaved" not in out, "nothing unsaved right after the save: %s" % out.get("unsaved")) + check(out.get("saved_steps") == ["OpenCode: code", "OpenCode: code (this run)"], "what it wrote: %s" % out.get("saved_steps")) + again = run_code("import bpy\nbpy.ops.wm.save_mainfile()") + check(again.get("saved_steps") == [], "a save with nothing pending says so: %s" % again.get("saved_steps")) + later = run_code("import bpy\nbpy.ops.wm.save_mainfile()\nbpy.data.objects['Brick'].location.x = 3") + check(later.get("unsaved", {}).get("file") == "ex06.blend", "a change after the save stays unsaved: %s" % later.get("unsaved")) + + +@test +def t06_a_reopened_rigid_body_bake_is_explained(): + empty() + path = os.path.join(SCRATCH, "baked.blend") + built = run_code( + "import bpy\nbpy.ops.mesh.primitive_cube_add(location=(0, 0, 2))\nbpy.ops.rigidbody.object_add()\n" + "s = bpy.context.scene\npc = s.rigidbody_world.point_cache\npc.frame_end = 30\n" + "with bpy.context.temp_override(scene=s, point_cache=pc):\n bpy.ops.ptcache.bake(bake=True)\n" + "bpy.ops.wm.save_as_mainfile(filepath=%r)\nbpy.ops.wm.open_mainfile(filepath=%r)" % (path, path)) + check(built["status"] == "executed", "built, baked, saved, reopened: %s" % built.get("message")) + program = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "plugin", "programs", "verify.py") + code = "import json\nPARAMS = json.loads(%r)\n" % json.dumps({"criteria": [{"expr": "frame", "op": "==", "value": 20}], "frame": 20}) + out = run_code(code + open(program, encoding="utf-8").read(), read_only=True) + caches = out["result"].get("caches") or [] + check(caches and caches[0]["cache"] == "rigid body world" and caches[0].get("outdated") is True, "flagged: %s" % caches) + check("when its file is opened" in caches[0].get("note", ""), "and explained: %s" % caches[0]) + + +@test +def u_an_apply_result_says_it_too(): + empty() + revision = scene()["revision"] + out = core.handle("apply", {"script_handle": app.script_handle(), "if_revision": revision, "command_id": "u-1", + "summary": "lamp", "operations": [{"op": "create_object", "args": {"kind": "empty", "name": "Lamp"}}]}) + check(out.get("status") == "applied", "applied: %s" % json.dumps(out)[:400]) + steps = out.get("unsaved", {}).get("opencode_steps", []) + check(len(steps) == 1 and steps[0].startswith("OpenCode: "), "its undo step named: %s" % out.get("unsaved")) + + +for fn in TESTS: + try: + fn() + results["passed"].append(fn.__name__) + except Exception as error: # noqa: BLE001 + results["failed"].append({"name": fn.__name__, "error": "%s: %s" % (type(error).__name__, error), + "trace": traceback.format_exc()[-1500:]}) +print("RESULT " + json.dumps(results), flush=True) diff --git a/integrations/blender/test/plugin.test.ts b/integrations/blender/test/plugin.test.ts index a6b0434..cb0dc76 100644 --- a/integrations/blender/test/plugin.test.ts +++ b/integrations/blender/test/plugin.test.ts @@ -27,7 +27,7 @@ async function plugin(input: Parameters[0] = {}): Promise { const other = await plugin() await other.rpc("advertise", announcement(old.endpoint, old.scriptHandle)) other.registry.attach(other.registry.hosts().offers[0]?.offerID as string, "ses_test") - await assert.rejects(other.tool("blender_context"), /no scene method: install OpenCode Link 0\.4\.4/) + await assert.rejects(other.tool("blender_context"), /no scene method: install OpenCode Link 0\.4\.5/) assert.ok(loaded) }) }) diff --git a/integrations/blender/test/publication.test.ts b/integrations/blender/test/publication.test.ts index ab954b8..4f8cf77 100644 --- a/integrations/blender/test/publication.test.ts +++ b/integrations/blender/test/publication.test.ts @@ -6,7 +6,7 @@ test("only Blender is publishable, with public access and trusted-publishing met const plugin = new URL("../plugin/", import.meta.url) const pkg = JSON.parse(readFileSync(new URL("package.json", plugin), "utf8")) assert.equal(pkg.name, "@neuralnomads/opencode-blender") - assert.equal(pkg.version, "0.4.4") + assert.equal(pkg.version, "0.4.5") assert.equal(pkg.private, undefined) assert.equal(pkg.publishConfig.access, "public") assert.equal(pkg.repository.url, "https://github.com/NeuralNomadsAI/opencode-integrations") diff --git a/package-lock.json b/package-lock.json index 460f882..2765099 100644 --- a/package-lock.json +++ b/package-lock.json @@ -39,7 +39,7 @@ }, "integrations/blender/plugin": { "name": "@neuralnomads/opencode-blender", - "version": "0.4.4", + "version": "0.4.5", "license": "MIT AND GPL-3.0-or-later", "devDependencies": { "@opencode/plugin": "2.2.5", diff --git a/spec/README.md b/spec/README.md index d18ef52..f88646e 100644 --- a/spec/README.md +++ b/spec/README.md @@ -19,9 +19,9 @@ The integration's `package.json` carries a marker under `opencodeIntegration`, r "host": { "app": "blender", "protocol": 1, - "range": "^0.4.4", + "range": "^0.4.5", "appVersions": ">=5.3", - "payload": "host/blender/opencode_link-0.4.4.zip", + "payload": "host/blender/opencode_link-0.4.5.zip", "sha256": "" } }