Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion catalog.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.7" },
"host": { "protocol": 1, "range": "^0.4.8" },
"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"] }
Expand Down
15 changes: 14 additions & 1 deletion integrations/blender/host/opencode_link/blender_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,12 @@ def new_script_handle():


class _Job(object):
__slots__ = ("fn", "lock", "started", "done", "result", "error", "cancelled")
__slots__ = ("fn", "lock", "started", "done", "result", "error", "cancelled", "label")

def __init__(self, fn):
self.fn = fn
# The host method whose request queued it (core.handle names its request thread).
self.label = getattr(threading.current_thread(), "opencode_method", None)
self.lock = threading.Lock()
self.started = threading.Event()
self.done = threading.Event()
Expand Down Expand Up @@ -160,6 +162,7 @@ def __init__(self, code_execution_allowed):
# Set by the add-on: schedules a hot reload from disk (the `reload` host method).
self.reload_request = None
self._jobs = queue.Queue()
self._running = None # (host method, monotonic start) of the main-thread job running now
self._quiet = 0
# A hot reload carries the revision over: the document did not change.
self._revision = process_state().__dict__.pop("revision", 0)
Expand Down Expand Up @@ -401,6 +404,14 @@ def on_main(self, fn):
raise job.error
return job.result

def running(self):
"""Any thread: the request Blender's main thread is running now, and since how long (status method)."""
current = self._running
if current is None:
return {"busy": False, "queued": self._jobs.qsize()}
label, since = current
return {"busy": True, "running": label, "seconds": round(time.monotonic() - since, 1), "queued": self._jobs.qsize()}

def drain(self, budget=0.05):
"""Runs queued requests on the main thread (timer in the interface, pump in background mode)."""
self.refresh_document()
Expand All @@ -414,6 +425,7 @@ def drain(self, budget=0.05):
if job.cancelled:
continue
job.started.set()
self._running = (job.label, time.monotonic())
try:
with self.quiet():
job.result = job.fn()
Expand All @@ -422,6 +434,7 @@ def drain(self, budget=0.05):
except Exception as error: # noqa: BLE001
job.error = HostFailure("internal", str(error))
finally:
self._running = None
job.done.set()
if time.monotonic() > deadline:
return
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
schema_version = "1.0.0"

id = "opencode_link"
version = "0.4.7"
version = "0.4.8"
name = "OpenCode Link"
tagline = "Lets OpenCode work on this Blender session"
maintainer = "NeuralNomads"
Expand Down
8 changes: 8 additions & 0 deletions integrations/blender/host/opencode_link/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
RELAUNCH_METHOD = "relaunch"
# Lifts a quarantine once the scene was read again (the revision of that read).
RELEASE_METHOD = "release"
STATUS_METHOD = "status"
QUARANTINED = ("OpenCode Link is quarantined: a failed change could not be proven undone. Read the scene "
"(blender_context shows what may have changed), then release it with that read's revision.")
# Methods whose results carry the errors and warnings Blender reported during the call.
Expand Down Expand Up @@ -230,6 +231,8 @@ def capabilities(self):
if hasattr(self.app, "thin_context"):
methods.append(SCENE_METHOD) # after the earlier methods: their order stays as it was
methods.append(RELEASE_METHOD)
if hasattr(self.app, "running"):
methods.append(STATUS_METHOD)
operations = []
listed = dict(self.operations, **(self.native_operations if self._native() else {}))
for name in sorted(listed):
Expand All @@ -247,6 +250,7 @@ def capabilities(self):

# -- dispatch (called from the listener's request threads) --------------------------------
def handle(self, method, params):
threading.current_thread().opencode_method = method # names the main-thread job status reports
if method not in REPORTING:
return self._dispatch(method, params)
mark = console.capture().cursor()
Expand Down Expand Up @@ -300,6 +304,10 @@ def _dispatch(self, method, params):
return self.app.on_main(lambda: self._relaunch(params))
if method == RELEASE_METHOD:
return self.app.on_main(lambda: self._release(params))
if method == STATUS_METHOD and hasattr(self.app, "running"):
# Answered on this request thread, never through the main thread: whether Blender's main thread is
# running a request, which one and for how long (a call that timed out is still running there).
return self.app.running()
raise HostFailure("method_not_found", "Unknown host method.")

def _reports(self, params):
Expand Down
2 changes: 1 addition & 1 deletion integrations/blender/host/ops.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"addon": "opencode_link",
"version": "0.4.7",
"version": "0.4.8",
"protocol": 1,
"method": "apply",
"wire": "params.operations: [{op, args}] with every op below (an edit batch); unknown ops and fields are refused",
Expand Down
5 changes: 3 additions & 2 deletions integrations/blender/plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,13 @@ Add-on settings (Preferences ▸ Add-ons ▸ OpenCode Link): _OpenCode service_

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, the context the code had, the operators of its group whose poll passes, and the context members (with their path) or editor area that make it pass, found by trying `poll()` only. 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 (`<file name>.crash.txt` in its temporary folder), instead of an unreachable host.
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, the context the code had, the operators of its group whose poll passes, and the context members (with their path) or editor area that make it pass, found by trying `poll()` only. 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 crashes, the call running then stops waiting within two seconds and says so with the crash report Blender wrote (`<file name>.crash.txt` in its temporary folder; only the report named after its own document counts, since every Blender of a user writes there); on Windows its process stays open behind Blender's crash window. A Blender closed without a report (closed, or ended by another program), one whose offer stopped while its process runs, and a call that outlasts its wait while Blender still runs it (the add-on's `status` answers off Blender's main thread, with the request running and for how long) are said as such; after its Blender crashed or closed, a conversation never attaches another Blender by itself.

## Blender limits

- Blender 5.3 or later; edits run in Object mode only.
- Two conversations may attach the same Blender: each batch is checked against the document's revision.
- Two conversations may attach the same Blender: each batch is checked against the document's revision, and the attach that makes it shared says so (`shared`).
- Blender 5.3 closes when a script sets `use_disk_cache` on the rigid body world's point cache of a saved file (a Blender defect, outside OpenCode Link).
- The code-change fingerprint that keeps the revision current does not read mesh vertices, modifier and node values or settings below one nested level. A `read_only` run is judged by its content instead (poses, mesh vertices, shape key values, constraint influences, material node values): one that puts everything back is no change.

## Earlier installation
Expand Down
Binary file not shown.
8 changes: 4 additions & 4 deletions integrations/blender/plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@neuralnomads/opencode-blender",
"version": "0.4.7",
"version": "0.4.8",
"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",
Expand Down Expand Up @@ -60,10 +60,10 @@
"host": {
"app": "blender",
"protocol": 1,
"range": "^0.4.7",
"range": "^0.4.8",
"appVersions": ">=5.3",
"payload": "host/blender/opencode_link-0.4.7.zip",
"sha256": "5ff8ba71be6cd7e146e8e1367e082d323c30817c1a6ed38af3743a2470c397dc"
"payload": "host/blender/opencode_link-0.4.8.zip",
"sha256": "d5b94052efdc503c2cd3e3ff183913733b22a52d9765a5e06e03d17d5f95a01b"
}
}
}
72 changes: 52 additions & 20 deletions integrations/blender/plugin/src/closed.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,81 @@
// A Blender that closed under a conversation: its process gone, and the crash report Blender wrote, if any. The
// add-on's hello names its process and the folder Blender writes "<file name>.crash.txt" to; a later call that
// finds the Blender unreachable, or its offer gone, says so instead of a bare "unreachable".
// What became of a Blender that stopped answering a conversation: crashed (Blender wrote its crash report; on
// Windows its process stays open behind Blender's crash window), closed (its process gone, no report: closed, or
// ended by another program), still running a long call, or no longer answering. The add-on's hello names its
// process, the folder Blender writes "<file name>.crash.txt" to, and its document. Every Blender of a user shares
// that folder: only the report named after this Blender's document counts.

import { readdirSync, statSync } from "node:fs"
import { join } from "node:path"

import { isAlive } from "./tasks.ts"

export type HostProcess = { pid: number; tempDir: string; label?: string; since: number; offerID?: string }
export type HostProcess = {
pid: number
tempDir: string
label?: string
since: number
offerID?: string
document?: string
}

export function readProcess(hello: unknown, label?: string, now = Date.now()): HostProcess | null {
const found = (hello as { process?: { pid?: unknown; temp_dir?: unknown } } | null)?.process
const read = hello as { process?: { pid?: unknown; temp_dir?: unknown }; document?: unknown } | null
const found = read?.process
if (!found || !Number.isInteger(found.pid) || (found.pid as number) <= 0) return null
if (typeof found.temp_dir !== "string" || !found.temp_dir) return null
return { pid: found.pid as number, tempDir: found.temp_dir, label, since: now }
const document = typeof read?.document === "string" && read.document ? read.document : undefined
return { pid: found.pid as number, tempDir: found.temp_dir, label, since: now, document }
}

// The name Blender gives its crash report: the file's name, or "blender" for a file never saved.
function reportName(host: HostProcess) {
return `${host.document ? host.document.replace(/\.blend$/i, "") : "blender"}.crash.txt`
}

// The newest crash report written in the process's crash folder since this conversation first reached it.
export function crashReport(host: HostProcess): string | null {
// This Blender's crash report when written since `after` (by default since this conversation first reached it).
export function crashReport(host: HostProcess, after = host.since): string | null {
const wanted = reportName(host).toLowerCase()
let names: string[]
try {
names = readdirSync(host.tempDir)
} catch {
return null
}
let newest: { path: string; time: number } | null = null
for (const name of names) {
if (!name.endsWith(".crash.txt")) continue
if (name.toLowerCase() !== wanted) continue
const path = join(host.tempDir, name)
try {
const time = statSync(path).mtimeMs
if (time >= host.since - 1_000 && (!newest || time > newest.time)) newest = { path, time }
if (statSync(path).mtimeMs >= after - 1_000) return path
} catch {
// removed meanwhile
}
}
return newest?.path ?? null
return null
}

const again = "Open Blender again and attach it (blender_hosts)."

// Crashed or closed; null while its process lives without a new crash report.
export function closedMessage(
host: HostProcess,
alive: (pid: number) => boolean = isAlive,
after = host.since,
): string | null {
const name = host.label ? ` (${host.label})` : ""
const report = crashReport(host, after)
const living = alive(host.pid)
if (report)
return `Blender crashed${name}: crash report ${report}. ${
living
? `Its process ${host.pid} is still open (Blender's crash window) and answers nothing.`
: `Its process ${host.pid} has ended.`
} Changes after its last save are lost. ${again}`
if (living) return null
return `Blender closed${name}: its process ${host.pid} has ended, with no crash report in ${host.tempDir} (closed, or ended by another program). ${again}`
}

// null while the process lives: then the usual unreachable message stands.
export function closedMessage(host: HostProcess, alive: (pid: number) => boolean = isAlive): string | null {
if (alive(host.pid)) return null
// Its offer is gone while its process lives without a crash report: the add-on stopped renewing it.
export function silentMessage(host: HostProcess) {
const name = host.label ? ` (${host.label})` : ""
const report = crashReport(host)
return report
? `Blender closed${name}: its process ${host.pid} has ended. Crash report: ${report}. Open Blender again and attach it (blender_hosts).`
: `Blender closed${name}: its process ${host.pid} has ended, with no crash report in ${host.tempDir}. Open Blender again and attach it (blender_hosts).`
return `Blender${name} no longer offers itself: its process ${host.pid} still runs but stopped renewing its offer (frozen, or OpenCode Link was disabled). blender_hosts lists the Blenders offered.`
}
Loading
Loading