From 5facbba3bb93fe0b9cc0810f95804af62ba244fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 14 Nov 2026 20:55:19 +0100 Subject: [PATCH 1/2] fix(blender): OpenCode for Blender 0.4.5, say what the saved file lacks In the 0.4.4 exercises (ex06, ex09) the agent checked the open document and concluded, while the saved file lacked its last changes (the robot's pose, the light-linking receiver) and the physics cache it measured was outdated. 0.4.5 adds short facts to existing results; nothing is imposed on the agent. unsaved: when the open document differs from its file, the results of blender_context, blender_apply, blender_execute_code and blender_verify say so: the file's name (never_saved for a new document) and the OpenCode undo steps pushed since its last save or load (changes made by hand are not listed). The adapter keeps those steps (barriers excluded) and clears them on a save of the open file or a load. blender_save says what it wrote: bytes and wrote_steps, the OpenCode steps now in the file; after a copy, what the open file still lacks. Blender calls the save handler for a copy too, with the copy's path: a copy no longer counts as a save of the open file (0.4.4 took it for one, and a background Blender then called the open file saved). caches: blender_verify names the simulation caches its checked frames read without a current bake: rigid body world, cloth, soft body, dynamic paint, simulated particles and fluid domains, not baked, baked but outdated (made before a later change), or baked without a checked frame. On the exercise's own file, frame 120 now reports the rigid body cache "cache is outdated!". A code run that opens a file pushes no undo step into it (its barrier was the old document's), so an opened file is as saved instead of modified. Validation: ops045_tests.py (5 tests) and one plugin test in a background Blender 5.3 fail on 0.4.4 and pass on 0.4.5; a trial through the plugin on copies of the exercises' files (ex06: outdated rigid cache at frame 120; ex09: a change after the save named in context, execute_code and verify, then blender_save's wrote_steps, nothing unsaved after). lint, typecheck, npm test, build, check:markers, trace scan, the Blender suites and native sessions with OpenCode 2.2.5 pass. --- catalog.json | 2 +- .../blender/host/opencode_link/addon.py | 4 +- .../blender/host/opencode_link/blender_app.py | 34 +++- .../host/opencode_link/blender_manifest.toml | 2 +- .../blender/host/opencode_link/core.py | 20 ++- integrations/blender/host/ops.json | 2 +- integrations/blender/plugin/README.md | 28 ++-- ...link-0.4.4.zip => opencode_link-0.4.5.zip} | Bin 855894 -> 858400 bytes .../plugin/methods/tools/blender_context.json | 2 +- .../plugin/methods/tools/blender_save.json | 2 +- .../plugin/methods/tools/blender_verify.json | 2 +- integrations/blender/plugin/package.json | 8 +- .../blender/plugin/programs/verify.py | 59 +++++++ .../blender/plugin/src/integration.ts | 40 +++-- integrations/blender/test/blender.test.ts | 55 +++++++ .../blender/test/blender/ops045_tests.py | 146 ++++++++++++++++++ integrations/blender/test/plugin.test.ts | 4 +- integrations/blender/test/publication.test.ts | 2 +- package-lock.json | 2 +- spec/README.md | 4 +- 20 files changed, 366 insertions(+), 52 deletions(-) rename integrations/blender/plugin/host/blender/{opencode_link-0.4.4.zip => opencode_link-0.4.5.zip} (99%) create mode 100644 integrations/blender/test/blender/ops045_tests.py 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..a483dc1 100644 --- a/integrations/blender/host/opencode_link/blender_app.py +++ b/integrations/blender/host/opencode_link/blender_app.py @@ -165,7 +165,9 @@ 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._handle = new_script_handle() self._main = threading.main_thread() self.background = bool(bpy.app.background) @@ -233,12 +235,32 @@ 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 = [] self.refresh_document() + 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,7 +345,13 @@ 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 @@ -416,6 +444,8 @@ 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() + if not message.startswith("OpenCode: before "): # a barrier marks a start, not a change + 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..5326776 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,8 @@ 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 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 +921,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 +959,8 @@ def finish(deferred=None, deferred_error=None): output["undo_step"] = done.undo_step if done.saved: output["saved"] = True + if unsaved_before and unsaved_before.get("opencode_steps"): + output["saved_steps"] = unsaved_before["opencode_steps"] # what that save wrote of OpenCode's 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..73e7862 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); `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) 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, 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 4a7a8d4b951c3610a84ab781b5f63563c7546e7b..6276bebed176a40cb4d2c5cafe7171d129dba0d8 100644 GIT binary patch delta 2915 zcmb7Ge{3699Y5c*edix9apfdU6GmU$u60V{q-vI>Zhnw1YP271GSRJ3v*2FrbL_^x zGrmi$2$g^;G$1euj_!+EZOMctKrJjZ2#-~aqEQAzV$FaGO@*dYi-b1FC}K$4((v9p zJ3q?)09#M?`@Z-6yzh_C=iOa>wr%!8+uV_9&)DUE{(dMT2t)J7roXw}dUufz- ztao{>3vbu@XgydQM9~t^k&z=Zn>99)1~_|MZnEAwQw6gJydLY`rAKOFADKVgL5_wB z9#}$6((Gwvtk*xRo;s3JOdb^vD5J#3jV4l{Mc~GS9-qjnnn@DrWKzu=B$?N|&6t zLc29ON$4~|S)me5H%TT#_M-bk)LW!r>Vu;*^$l^Y{sT>u~dKXKQrC3pf6OfcNP0Lc7_48!{nY~E1w%&Aa=N@;f$M$8! zVZAY|g%5*)z7jPIZc`JM^nPeN3x-NbvFXi)MfqV1jifbGr`@(j-miCYocYD&+xS>X zD@^pPwOQ3Llrc48m`dI>n4H3)GI640RHcGbNr*~`Dq10ajLRzdaf8meR}%-K zs^k=c1yu}w)U6P#^*>hMUc4d*i&u(&Jt_A0)|CiJslrcDa=9``VeTDqi&R>N*j`larKy+a z$B?J`q0)r6u?$qYz_?6xjSA8jCtR-OYlG-Xu36RtQsy@N+2g4xcKuA;;rM?-+9H=j zvU2~ff|+jQt>mI!3kl{PL^TiyAqg~sa|2JA6R!A+FdA|~#S>2V zRDMDuWx~+Tr)V2lcJ|#;Zfrp@?5r}0)ueVB`?yV03xwV}BuzVCreS1*xbkX_)`&8) zi`d;}ec&O58{xt`;^t;P2{jV_lxbz+;+734v=%lHFUFxJOoxXKFCD(3tH=N4OKYzN z04x4}$E$FC#ZT(jp7?@LA*}y==X4!z;Ho^`gKNaMdQTt0y<)KM^cmdY6(1LcxULy` z1~xfx)yLLkDhSeg6ye2F;CJ9X;!h7luLFNlEIbCM9JpId{03feP{7!qz%Al#)bDgc zzleLpkpO&2#GUAa<4!oFIO`!<*}L;XZNOad^Uod(azH zZqK@Cd^7d1=)!I2F9#)f^kJzUzSkz#KvtqL47q6xcMfxVn{E0DGyVE#Y3pLU9E8u` zFZ&@N;azBXv}8ZnA$vfPa66hlUNYSil{ecE*CYz@{jW+-pOSXjmg%RYfPbxs{ojHC z84rm5Z^NvNhsD3W!hUOk^vT|*FH*U*dhjms{_CsO3V7iUk{_O8=I58-B@cBz@GtOr z@nh(`Aj8UgQUtDhXhye0Ie^zrdd|-m>!A|Kwe}8&j~4m6Ti_laJ}lp8k%f#h+5$ZT z@-{ox^KAWQC;ZBXqrSGId_6{A*g!$J8bW@$dT<=N{gg8^U!be$EPWw^AFlX=V6nxM z&%+CT+Mkz$@U9>46E9zaW{jian+uS}c%OgzfLG9Sv4Ud8Q?}cygWmPkIdv4SV+t^O z3P=TR7oYhe3{~I`&)IWc!BmX#(qZQ-aGexv<$o8igW8^-iJjv`QgWM zL9e`cfvvxme#Etmyg^RyS<@sNYnoUwqwnn*49%XCq}g-ENFQs-7!xO1O2%}H&5ryG z^B7;BVlQ+Uxdr@jTgjMl8%G!M>kNCFxeHlcwjn>kGz>k+!-o18f7x!FY~atSdoC{L z0ycqr1ndHefXQnDx`4yDxZJt@ySe-*Xw)Jfz$Y5bi_N8$B$ssOSH$lcCE{k9o3bRC z2;AA1W@?epDZ?JB$4fdbVX-WZ=oC-RC6y%QF2`suliD{IH=^G`K1}NrWmlhs!$FPg zvz1uopnCrCFvqU5Jc#iyd2q}jBp-}n#BBB6;P5)BftBod#!1WABL%$gq$k+1?=fNW ziOYzPSZKG598nYdGKn%#J=?tyljhmlhj}icYdwL2i|W{wDU@A;KOe`Wi<&pBO{UYG6 z|0)=Asxj=8Ri9;e#V-b3V5-TdEb6SFl%L(|ZSRJt`hZ0z0%CM%KI#JWEQ_XaAV5o5 zR~A16#GlYtfEuJF`go79b#Ch1+HJjfTTqxPhp{avUg4UC<3XxrGhgAqpfGz*BNY<$ z@G`s>qQ!hLtE0SL_hTp|?*F50_$x$@I>z4ArQ*i!&94{Rk#JG~jbSl!v>&-JrIi(@ hb!lryCq~2M$ERjTdK#y~Vx_~EAV(--_uMky=zkjXLZkoy 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..b7aa693 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": "b2ef393d4717b68687319b4d780f4afe885a763f597e9efb754fefc4173afba9" } } } diff --git a/integrations/blender/plugin/programs/verify.py b/integrations/blender/plugin/programs/verify.py index 3659990..0693a4c 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,64 @@ 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) + 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..8c480d7 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_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,29 @@ 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), + ...(out.saved_steps ? { 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 +597,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 +721,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..f317506 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 = 5 const folder = join(import.meta.dirname, "blender") type Result = { passed: string[]; failed: Array<{ name: string; error: string; trace: string }> } @@ -290,6 +292,59 @@ 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) + } 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..f15739c --- /dev/null +++ b/integrations/blender/test/blender/ops045_tests.py @@ -0,0 +1,146 @@ +"""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") + + +@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": "" } } From 14cc07fc5adf61210ad262d345d318c3c94bbe43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 14 Nov 2026 21:45:48 +0100 Subject: [PATCH 2/2] fix(blender): 0.4.5, saves inside a code run, restorations and reopened bakes The 0.4.5 trial (ex06, ex09) saved through execute_code (bpy.ops.wm.save_as_mainfile) rather than blender_save, in an interface Blender. Replayed there with the trial's own calls, on a desktop never shown: - every run that saved still answered unsaved: right after the save, inside the run, an interface Blender keeps is_dirty set until its next event loop (a background Blender keeps it after any undo step: a run that changed the document, then saved, answered unsaved there too; the tests saved without changing anything). A document whose revision is the one saved is now saved whatever is_dirty says, and a run that saved and changed nothing after it (its content compared with the one saved) leaves it so. - saved_steps listed "OpenCode: failed code": the step a failed run pushes is undone at once by its restoration, and is no change of the file. A run that changes then saves lists its own change ("OpenCode: code (this run)"). - blender_save after a save in code had nothing pending and returned no wrote_steps, read as missing: a save of the open file always says it, an empty list when nothing was pending (execute_code's saved_steps too). - verify listed no cache: the rigid body cache baked in that run was current (is_outdated false) at every verify. The QA read it outdated by reopening the file: Blender 5.3 flags every rigid body bake outdated when its file is opened (the cloth's stays current) and still plays its frames (same positions at frame 120). caches now says so in a note on that entry. Validation: three ops045 tests and the plugin test fail on the PR head (5facbba) and pass; the trial's sequence replayed in an interface Blender on the hidden desktop answers no unsaved after the save, saved_steps without restorations, wrote_steps [] then ["OpenCode: code"]. lint, typecheck, npm test, build, check:markers, trace scan, the Blender suites (22/22, extension 1/1) and native sessions with OpenCode 2.2.5 pass. --- .../blender/host/opencode_link/blender_app.py | 25 +++++++--- .../blender/host/opencode_link/core.py | 7 ++- integrations/blender/plugin/README.md | 28 +++++------ .../host/blender/opencode_link-0.4.5.zip | Bin 858400 -> 859561 bytes integrations/blender/plugin/package.json | 2 +- .../blender/plugin/programs/verify.py | 3 ++ .../blender/plugin/src/integration.ts | 5 +- integrations/blender/test/blender.test.ts | 5 +- .../blender/test/blender/ops045_tests.py | 45 ++++++++++++++++++ 9 files changed, 94 insertions(+), 26 deletions(-) diff --git a/integrations/blender/host/opencode_link/blender_app.py b/integrations/blender/host/opencode_link/blender_app.py index a483dc1..96c43f8 100644 --- a/integrations/blender/host/opencode_link/blender_app.py +++ b/integrations/blender/host/opencode_link/blender_app.py @@ -168,6 +168,7 @@ def __init__(self, code_execution_allowed): 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) @@ -244,8 +245,18 @@ def saved(self, path=None): 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.""" @@ -354,14 +365,15 @@ def loads(self): 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): @@ -444,7 +456,8 @@ 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() - if not message.startswith("OpenCode: before "): # a barrier marks a start, not a change + # 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): diff --git a/integrations/blender/host/opencode_link/core.py b/integrations/blender/host/opencode_link/core.py index 5326776..e222381 100644 --- a/integrations/blender/host/opencode_link/core.py +++ b/integrations/blender/host/opencode_link/core.py @@ -897,6 +897,8 @@ def _guarded(self, run, label, barrier): self._quarantine("failed %s: %s" % (label, error)) 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) @@ -959,8 +961,9 @@ def finish(deferred=None, deferred_error=None): output["undo_step"] = done.undo_step if done.saved: output["saved"] = True - if unsaved_before and unsaved_before.get("opencode_steps"): - output["saved_steps"] = unsaved_before["opencode_steps"] # what that save wrote of OpenCode's + # 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/plugin/README.md b/integrations/blender/plugin/README.md index 73e7862..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). `caches` names the simulation caches the checked frames read without a current bake (not baked, outdated, frames outside it); `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) 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. | +| 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,7 +129,7 @@ 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, and a run that opens a file pushes no step into it. +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. diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.5.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.5.zip index 6276bebed176a40cb4d2c5cafe7171d129dba0d8..70d9a9a052421687ea9fe587b8c96b7cf4cc2bd1 100644 GIT binary patch delta 2263 zcmZ`)eQZ-z6mQ>Sd);gAwr*|L4J3CRLOYfwz?jQ$Y*U00gb^@NHn6<4ciS6p?~T5< z!9ZDvgau=aNaVyobo?cvAvh$95|Kar3M6h*LHL6NV??6@l0fhyqUXN1b|XrYoA#c2 zK7Z$TPKQUT-#%S^;?y~L?a|7%LpxlqLpx4>d~WkhVk-SCl}H-8#dHgLN95qi+1DDp zgB5f=f1&LIRMBZmFVi14QjDhibQ)D?GV?pBXqu{bQtl?vqo{g^s^HB5wtBXfcIxKw0 zc>EGInPq7#!NbSmSzjj8I^wo4TNoi=!Bh7|sv%4t$#N*YnLvbgaMWN};J09Q3h zL2N^|&g?u)F<=Q*XuFc!(wW8-Q+C6)FxHFi;XTnEbXUP=qMOc}#@ZIn{B0`o@4p>| z#sMJ!t7f=s4s87)R5(fIM21NRw*DT3wT;c{J>7#)8> zs6FN5dmzIXSbbaw%Tu!k{=42FY`!Gqt(+1voL*YNd1Wt#?53~>l9#}#@ZcF6{ijxp z6d*KD!|`UZyvfnzpg1FDZ!Qfx$hV+VpN$LOfI0$J$H#~D^y0W_s%gdIuwbQFaU6u)`s2ZJT0rKJ5O+TT;_D4MLk&QLNA8 z`z03H#1Z1%if5{|_Z3OKlg85u7fQ^JaCU_RWFhRS^jc}EJAKec$AN7uY1xh}t7na?I;e3?G=EK!|vP^te z&xOYB+yE>oAeCa9M}nK86oOrN6QUH36_9GdSO-@N$VOpk1OJ`{;|-otxbDYPzipKY zeN)A*OE?Or3&~1hZ>MuvoRor&_UqmEX$K5PVbD*S#G3sQoO?;Cgr!C3_isN!Fn$sZkrq16cCi*r11#^;#{gKkf;W3VNFjw=1Oe32tMk0NQoY>#c5DDyn*h|7cMy1N?c zgJiwX(*&;uNuBV~v+!jQiEz;XPl(jY(Yt&n2YBJNHG|m1d^Vmrg>tj|8DH tj6Ua_fQ?~NEgilnyO8uS5hek6hrg^(z~^C1>Benvmy*)lBq7+Ne*se&-yHw| delta 1248 zcmY*XTTC2P7@j?|yE8lNVP~1W!0r+bOSQH^pcmQ|L4;QNP`2d(Y{k-L*d1VDnc40P ztUP!NF~n438k+nyYM?PqL^K+)K~pan<3njukq0$3#(JR-Z3t~sO>D9C47-MUCSU%X z?|lE4?>}><&+VN0Xy=D#7liDt>Pc6YVO-hSFBiIl5M6URpv!70pG{ry6imE)vwZf@ zt!wVC=9Ho)l+0$GB=uM#nK4EyiSkTbNgE`ok{&re*q70U)dU&R5=te>_A42MBn^S& zmu|?TI?)w_$i0S=A+kD3s9Ynup`@XnvykdKVwhc(L?#I>K0KtT29?D7WwlR95Iw2J zO-KDdOX#*+LN21qBTAww91gGZAokfkFvVFO27jMjw5=zdxN+MH-J2Z()KswrHdQmo zLvXKM@J}3D_K6KNRjRitmQhBMdQwy8cJLO56Q(_uKp=cDt*CqGM0KP`>DA~+;VpH9 zR1g^&Jr-YKB{9upk_!o6P1~i3i_6lu*K3*cdQn40`1VKd&C81nb9r&@$T*6eh0-Dm zH}^;bTjYYP3rGmW^2Rc~yJ2;Gnmh%ot*jR+mIOc49AJ4k-^z*){9p2PSfc^sG+@lU zM?KtShRec%RR}d?Iy> z{R~fubidCEuZ#4&ON5_9T+iMau)=B08iZOm-in@E1lf%n*=v7U;lv%Q4?Z>7wgOmo z<7V`HC2T389&PoIG;7(bFkOTjQQ1YfT7(Ki-2@zBV^qX!kE>4a42vIWecb;iuX&tALB~LDcdm94*Ej=sgC+ z5*&gd8!zQ#5jQV7H-epZnu4R~of1fw;CAlUYMx2SJwR&tO|V)*ll@T-!2qs9J3HY} z07p=C5KfqN@*W;8+#xTq@li;nH{T zSr9*pj<>+yLA)D{b;9-#ZWMaP1SXx);)t6J!Uwo)7^SFSsmY%-%%rAOQL+wA6W_4KO|8Rimi{)B%4Coq6L diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index b7aa693..b503940 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -63,7 +63,7 @@ "range": "^0.4.5", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.5.zip", - "sha256": "b2ef393d4717b68687319b4d780f4afe885a763f597e9efb754fefc4173afba9" + "sha256": "82ca90eca45d454f0d1fe403c2c4dd4cffc1d3990e1bd6e374ab515314adfb73" } } } diff --git a/integrations/blender/plugin/programs/verify.py b/integrations/blender/plugin/programs/verify.py index 0693a4c..06be24b 100644 --- a/integrations/blender/plugin/programs/verify.py +++ b/integrations/blender/plugin/programs/verify.py @@ -631,6 +631,9 @@ def point_cache(owner, pc): 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: diff --git a/integrations/blender/plugin/src/integration.ts b/integrations/blender/plugin/src/integration.ts index 8c480d7..e968d81 100644 --- a/integrations/blender/plugin/src/integration.ts +++ b/integrations/blender/plugin/src/integration.ts @@ -172,7 +172,7 @@ 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_steps?: string[] } +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 = {}) { @@ -430,7 +430,8 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) const out = await programRun(context, "save", args) return { ...(out.result as Record), - ...(out.saved_steps ? { wrote_steps: out.saved_steps } : {}), + // 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 } : {}), } } diff --git a/integrations/blender/test/blender.test.ts b/integrations/blender/test/blender.test.ts index f317506..c431018 100644 --- a/integrations/blender/test/blender.test.ts +++ b/integrations/blender/test/blender.test.ts @@ -19,7 +19,7 @@ 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 = 5 +const OPS045_TESTS = 8 const folder = join(import.meta.dirname, "blender") type Result = { passed: string[]; failed: Array<{ name: string; error: string; trace: string }> } @@ -340,6 +340,9 @@ describe("OpenCode Link in Blender (background)", { skip }, () => { 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() } diff --git a/integrations/blender/test/blender/ops045_tests.py b/integrations/blender/test/blender/ops045_tests.py index f15739c..fdad5c7 100644 --- a/integrations/blender/test/blender/ops045_tests.py +++ b/integrations/blender/test/blender/ops045_tests.py @@ -125,6 +125,51 @@ def u_a_file_opened_by_code_is_as_saved_and_gets_no_step(): 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()