diff --git a/catalog.json b/catalog.json index d00569f..c3f0403 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.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"] } diff --git a/integrations/blender/host/opencode_link/blender_app.py b/integrations/blender/host/opencode_link/blender_app.py index 96c43f8..5e33f76 100644 --- a/integrations/blender/host/opencode_link/blender_app.py +++ b/integrations/blender/host/opencode_link/blender_app.py @@ -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() @@ -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) @@ -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() @@ -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() @@ -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 diff --git a/integrations/blender/host/opencode_link/blender_manifest.toml b/integrations/blender/host/opencode_link/blender_manifest.toml index 32c0f6f..b4a1603 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.7" +version = "0.4.8" 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 e222381..9de724d 100644 --- a/integrations/blender/host/opencode_link/core.py +++ b/integrations/blender/host/opencode_link/core.py @@ -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. @@ -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): @@ -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() @@ -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): diff --git a/integrations/blender/host/ops.json b/integrations/blender/host/ops.json index 64b9808..830d8a8 100644 --- a/integrations/blender/host/ops.json +++ b/integrations/blender/host/ops.json @@ -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", diff --git a/integrations/blender/plugin/README.md b/integrations/blender/plugin/README.md index 9732ad1..94fcdbf 100644 --- a/integrations/blender/plugin/README.md +++ b/integrations/blender/plugin/README.md @@ -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 (`.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 (`.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 diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.7.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip similarity index 99% rename from integrations/blender/plugin/host/blender/opencode_link-0.4.7.zip rename to integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 24e6ab0..03b5163 100644 Binary files a/integrations/blender/plugin/host/blender/opencode_link-0.4.7.zip and b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip differ diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index ccec4cf..849e5d0 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -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", @@ -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" } } } diff --git a/integrations/blender/plugin/src/closed.ts b/integrations/blender/plugin/src/closed.ts index 94c8402..6616a68 100644 --- a/integrations/blender/plugin/src/closed.ts +++ b/integrations/blender/plugin/src/closed.ts @@ -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 ".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 ".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.` } diff --git a/integrations/blender/plugin/src/integration.ts b/integrations/blender/plugin/src/integration.ts index c2814fd..353f2b4 100644 --- a/integrations/blender/plugin/src/integration.ts +++ b/integrations/blender/plugin/src/integration.ts @@ -9,7 +9,7 @@ import type { Plugin } from "@opencode/plugin" import type { ToolContext } from "@opencode/plugin/promise/tool" import { type AttachmentStorage, createAttachments, trackAdvertise } from "./attachments.ts" -import { closedMessage, type HostProcess, readProcess } from "./closed.ts" +import { closedMessage, crashReport, type HostProcess, readProcess, silentMessage } from "./closed.ts" import { extensionsDir, inspectHost, installHost } from "./host-install.ts" import { type BindingAuthority, @@ -34,7 +34,7 @@ import { type EntryPut, methodAttacher } from "./method.ts" import { type BlenderOptions, readOptions } from "./options.ts" import { defaultPathEnv, methodsDir, type PathEnv, packageRoot } from "./paths.ts" import { type ProgramName, programCode } from "./programs.ts" -import { addTask, cancelTask, getTask, type RenderStart, taskStatus } from "./tasks.ts" +import { addTask, cancelTask, getTask, isAlive, type RenderStart, taskStatus } from "./tasks.ts" import { validatePlan } from "./validate.ts" export const APP = "blender" @@ -69,6 +69,10 @@ export const LAB_TOOLS = [ const MAX_TEXT = 100_000 const VERIFY_TIMEOUT_MS = 600_000 +// The status method answers off Blender's main thread: no answer within this long means the add-on is frozen. +const STATUS_TIMEOUT_MS = 3_000 +// How often a running call looks for its Blender's crash report. +const CRASH_POLL_MS = 2_000 // A save that failed while the .blend was briefly held by another process, retried once after SAVE_RETRY_MS. export const TRANSIENT_SAVE = /unable to make version backup|file saved with @/i export const SAVE_RETRY_MS = 1_000 @@ -315,9 +319,31 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) const reached = new Map() const helloed = new Map() // sessionID -> the offer whose hello was read const wsl = deps.wsl ?? (() => isWslDaemon()) - const closedFor = (sessionID: string) => { + // Its offer gone: crashed, closed, or alive without renewing its offer. Never another Blender in its place. + const goneFor = (sessionID: string) => { const host = reached.get(sessionID) - return host && !wsl() ? closedMessage(host) : null + if (!host || wsl() || registry.hosts().offers.some((offer) => offer.offerID === host.offerID)) return null + return closedMessage(host) ?? silentMessage(host) + } + // A call that failed, timed out or was refused as busy: what Blender is doing. Its crash report (written since + // this conversation reached that process), the process gone, or the request its main thread runs now (the status + // method answers off the main thread). + const diagnose = async (sessionID: string, bound: HostBinding, code: string) => { + const host = reached.get(sessionID) + if (!host || wsl()) return null + const closed = closedMessage(host, isAlive) + if (closed || code === "unreachable" || !bound.methods.includes("status")) return closed + try { + const status = (await requestHost(bound.endpoint, "status", {}, { timeoutMs: STATUS_TIMEOUT_MS })) as { + busy?: boolean + running?: string + seconds?: number + } + if (!status.busy) return null + return `Blender is still running ${status.running ?? "a request"} (${status.seconds ?? "?"} s so far): it goes on in Blender, nothing is lost. blender_context answers once it has finished; read it before acting again.` + } catch { + return `Blender does not answer: its process ${host.pid} runs, but OpenCode Link answered nothing within ${STATUS_TIMEOUT_MS / 1_000} s (frozen?).` + } } const remember = async (context: ToolContext, held: Ticket) => { if (helloed.get(context.sessionID) === held.bound.offerID) return @@ -348,6 +374,9 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) bound = registry.binding(context.sessionID) } if (!bound) { + // Its Blender crashed or closed: said, and no other Blender attaches itself in its place. + const gone = goneFor(context.sessionID) + if (gone) throw new Error(gone) const offers = registry.hosts().offers const only = offers.length === 1 ? offers[0] : undefined if ( @@ -362,8 +391,6 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) } } if (!bound) { - const closed = closedFor(context.sessionID) - if (closed) throw new Error(closed) if (!offers.length) throw new Error("No Blender is offered: open Blender 5.3 or later with the OpenCode Link add-on enabled.") const list = offers @@ -401,16 +428,36 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) ) } await remember(context, held) + // A crash ends the wait at once: on Windows a crashed Blender stays open behind its crash window and its + // connection with it, so the call would wait its whole timeout. Its crash report is watched meanwhile. + const host = wsl() ? undefined : reached.get(context.sessionID) + const stop = new AbortController() + const abort = () => stop.abort() + context.signal.addEventListener("abort", abort) + let crashed: string | null = null + const watch = host + ? setInterval(() => { + crashed = crashReport(host) ? closedMessage(host, isAlive) : null + if (crashed) stop.abort() + }, CRASH_POLL_MS) + : undefined try { return await requestHost( bound.endpoint, method, { script_handle: bound.scriptHandle, ...params }, - { signal: context.signal, timeoutMs }, + { signal: stop.signal, timeoutMs }, ) } catch (error) { - const closed = error instanceof HostError && error.code === "unreachable" ? closedFor(context.sessionID) : null - throw closed ? new Error(closed) : hostError(error) + if (crashed) throw new Error(crashed) + const said = + error instanceof HostError && ["unreachable", "timeout", "busy"].includes(error.code) + ? await diagnose(context.sessionID, bound, error.code) + : null + throw said ? new Error(said) : hostError(error) + } finally { + clearInterval(watch) + context.signal.removeEventListener("abort", abort) } } @@ -461,6 +508,8 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) if (!authority || !registry.current(authority)) throw new Error("This conversation's ownership is unverifiable: try again.") out.detached = registry.detach(context.sessionID).outcome + reached.delete(context.sessionID) // detached on purpose: its Blender closing later is no news here + helloed.delete(context.sessionID) } if (typeof args.attach === "string") { const offer = registry.hosts().offers.find((candidate) => candidate.offerID === args.attach) @@ -475,6 +524,9 @@ export async function setupBlender(ctx: Plugin.Context, deps: BlenderDeps = {}) if (out.attached === "attached") { await attachments.remember(context.sessionID) await attachMethod(context.sessionID) + if (heldElsewhere(offer.offerID, context.sessionID)) + out.shared = + "Another conversation is attached to this Blender too: both change the same document, and each call is checked against its revision." } } void legacy.refresh() diff --git a/integrations/blender/test/blender.test.ts b/integrations/blender/test/blender.test.ts index c412891..6fa2a05 100644 --- a/integrations/blender/test/blender.test.ts +++ b/integrations/blender/test/blender.test.ts @@ -3,13 +3,13 @@ // document. Skipped unless BLENDER_TEST_BIN names Blender. import assert from "node:assert/strict" -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs" +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { join } from "node:path" import { describe, it } from "node:test" import { requestHost } from "../plugin/src/kit.ts" import { blenderBin, installAddon, installTestAddon, isolatedRoot, runBlender } from "./helpers/blender.ts" -import { announcement, loadPlugin } from "./helpers/plugin.ts" +import { announcement, clock, loadPlugin } from "./helpers/plugin.ts" const skip = blenderBin ? false : "BLENDER_TEST_BIN is not set" // The tests of ops042_tests.py: one or more per friction of the journal's entries 47 to 62. @@ -285,7 +285,66 @@ describe("OpenCode Link in Blender (background)", { skip }, () => { // Where Blender writes its own report when it crashes (an unsaved file: blender.crash.txt). const report = join(iso.root, "tmp", "blender.crash.txt") writeFileSync(report, "# Blender 5.3.0\n") - await assert.rejects(plugin.tool("blender_context"), /Blender closed.*Crash report: .*blender\.crash\.txt/) + await assert.rejects( + plugin.tool("blender_context"), + /Blender crashed.*crash report .*blender\.crash\.txt\. Its process \d+ has ended/, + ) + } finally { + writeFileSync(stopFile, "") + await run.exited + await plugin.cleanup() + iso.cleanup() + } + }) + + it("a call that outlasts its wait says what Blender does: still running, crashed, or gone silent (0.4.8)", async () => { + const iso = isolatedRoot("blender-busy-") + const stopFile = join(iso.root, "stop") + installTestAddon(iso) + const run = runBlender(iso, join(folder, "serve.py"), [ + "--listen-only", + "--seconds", + "120", + "--stop-file", + stopFile, + ]) + const time = clock(Date.now()) + const plugin = await loadPlugin({ now: time.now }) + try { + let line: string | undefined + for (let attempt = 0; attempt < 600 && !line; attempt += 1) { + line = run + .output() + .split("\n") + .find((entry) => entry.startsWith("ENDPOINT ")) + if (!line) await new Promise((resolve) => setTimeout(resolve, 100)) + } + assert.ok(line, run.output().slice(-2000)) + const { port, token, script_handle } = JSON.parse(line.slice("ENDPOINT ".length)) + await plugin.rpc("advertise", announcement({ port, token }, script_handle)) + assert.equal(typeof JSON.parse(String((await plugin.tool("blender_context")).content)).revision, "number") + const sleep = (s: number) => `import time\ntime.sleep(${s})\nresult = {'slept': ${s}}` + // A long call: its wait ends, Blender's main thread is still running it (status answers off that thread). + await assert.rejects( + plugin.tool("blender_execute_code", { code: sleep(6), timeout_s: 2 }), + /Blender is still running execute_code \([\d.]+ s so far\): it goes on in Blender, nothing is lost/, + ) + await new Promise((resolve) => setTimeout(resolve, 5_000)) + assert.equal(typeof JSON.parse(String((await plugin.tool("blender_context")).content)).revision, "number") + // Sol ex06: Blender crashes during the call; on Windows its process stays open behind its crash window. + const report = join(iso.root, "tmp", "blender.crash.txt") + setTimeout(() => writeFileSync(report, "# Blender 5.3.0\n"), 500) + const started = Date.now() + await assert.rejects( + plugin.tool("blender_execute_code", { code: sleep(6), timeout_s: 30 }), + /Blender crashed.*crash report .*blender\.crash\.txt\. Its process \d+ is still open/, + ) + assert.ok(Date.now() - started < 5_000, "said at once, not after the call's whole wait") + await new Promise((resolve) => setTimeout(resolve, 5_000)) + rmSync(report) + // Its offer no longer renewed while the process lives: said, and no other Blender takes its place. + time.advance(16_000) + await assert.rejects(plugin.tool("blender_context"), /no longer offers itself: its process \d+ still runs/) } finally { writeFileSync(stopFile, "") await run.exited diff --git a/integrations/blender/test/plugin.test.ts b/integrations/blender/test/plugin.test.ts index 5e370bd..b320b9a 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 { assert.equal(loaded.registry.binding("ses_one"), null) }) + it("an explicit attach to a Blender another conversation uses says they share one document (0.4.8)", async () => { + const { loaded, offerIDs } = await offered() + const first = content(await loaded.tool("blender_hosts", { attach: offerIDs[0] })) + assert.equal(first.attached, "attached") + assert.equal(first.shared, undefined) + const second = content(await loaded.tool("blender_hosts", { attach: offerIDs[0] }, "ses_one")) + assert.equal(second.attached, "attached") + assert.match(second.shared, /Another conversation is attached to this Blender too: both change the same document/) + }) + it("never attaches by itself with two offered Blenders or an incompatible one", async () => { const two = await offered(2) await assert.rejects(two.loaded.tool("blender_context"), /No Blender is attached to this conversation/) @@ -845,7 +855,7 @@ describe("tools", () => { 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\.7/) + await assert.rejects(other.tool("blender_context"), /no scene method: install OpenCode Link 0\.4\.8/) assert.ok(loaded) }) }) diff --git a/integrations/blender/test/publication.test.ts b/integrations/blender/test/publication.test.ts index 520c0fe..45aec3b 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.7") + assert.equal(pkg.version, "0.4.8") 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/integrations/blender/test/unit.test.ts b/integrations/blender/test/unit.test.ts index 3ecab58..3fce58b 100644 --- a/integrations/blender/test/unit.test.ts +++ b/integrations/blender/test/unit.test.ts @@ -9,7 +9,7 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { describe, it } from "node:test" -import { closedMessage, readProcess } from "../plugin/src/closed.ts" +import { closedMessage, readProcess, silentMessage } from "../plugin/src/closed.ts" import { readPackage } from "../plugin/src/integration.ts" import { METHOD_TEXT, methodAttacher, resetMethodForTests } from "../plugin/src/method.ts" import { programCode } from "../plugin/src/programs.ts" @@ -162,24 +162,44 @@ describe("a Blender that closed", () => { assert.equal(readProcess({ process: { pid: -1, temp_dir: dir } }), null) assert.equal(readProcess({ process: { pid: 12, temp_dir: "" } }), null) assert.equal(readProcess({ revision: 1 }), null) - const host = readProcess({ process: { pid: 4242, temp_dir: dir } }, "Blender: shot.blend", Date.now()) + const hello = { process: { pid: 4242, temp_dir: dir }, document: "shot.blend" } + const host = readProcess(hello, "Blender: shot.blend", Date.now()) assert.ok(host) + assert.equal(host.document, "shot.blend") assert.equal( closedMessage(host, () => true), null, ) - const old = join(dir, "earlier.crash.txt") + const old = join(dir, "shot.crash.txt") writeFileSync(old, "") utimesSync(old, new Date(Date.now() - 60_000), new Date(Date.now() - 60_000)) + // 0.4.8: every Blender of a user writes its report in the same folder: another document's report is not this one's. + writeFileSync(join(dir, "ex05.crash.txt"), "# another Blender\n") assert.match( String(closedMessage(host, () => false)), - /^Blender closed \(Blender: shot\.blend\): its process 4242 has ended, with no crash report in /, + /^Blender closed \(Blender: shot\.blend\): its process 4242 has ended, with no crash report in .* \(closed, or ended by another program\)/, ) writeFileSync(join(dir, "shot.crash.txt"), "# Blender 5.3.0\n") - assert.match(String(closedMessage(host, () => false)), /Crash report: .*shot\.crash\.txt\. Open Blender again/) + assert.match( + String(closedMessage(host, () => false)), + /^Blender crashed \(Blender: shot\.blend\): crash report .*shot\.crash\.txt\. Its process 4242 has ended\./, + ) + // On Windows a crashed Blender stays open behind its crash window: the report says it all the same. + assert.match( + String(closedMessage(host, () => true)), + /crash report .*shot\.crash\.txt\. Its process 4242 is still open/, + ) + // A crash before the call started is not this call's. + assert.equal( + closedMessage(host, () => true, Date.now() + 10_000), + null, + ) + assert.match(silentMessage(host), /no longer offers itself: its process 4242 still runs but stopped renewing/) + const untitled = readProcess({ process: { pid: 7, temp_dir: dir } }, "Blender: Untitled", Date.now()) + writeFileSync(join(dir, "blender.crash.txt"), "") + assert.match(String(closedMessage(untitled ?? host, () => true)), /blender\.crash\.txt/) }) }) - describe("the working method", () => { it("is short, joins a conversation once, and never fails a Blender call", async () => { assert.ok(METHOD_TEXT.split("\n").length <= 10 && METHOD_TEXT.length < 1_000) diff --git a/package-lock.json b/package-lock.json index f24d2eb..76f84ae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -39,7 +39,7 @@ }, "integrations/blender/plugin": { "name": "@neuralnomads/opencode-blender", - "version": "0.4.7", + "version": "0.4.8", "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 feaaedb..2eee5ba 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.7", + "range": "^0.4.8", "appVersions": ">=5.3", - "payload": "host/blender/opencode_link-0.4.7.zip", + "payload": "host/blender/opencode_link-0.4.8.zip", "sha256": "" } }