From 0441dc0654f2533086a74cfd049ce42f60ff40ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 19 Nov 2026 23:20:37 +0100 Subject: [PATCH 01/13] feat(blender): chat with OpenCode in the Blender Console --- .../host/opencode_link/_console_opencode.py | 338 ++++++++++++++ .../blender/host/opencode_link/addon.py | 5 + .../blender/host/opencode_link/advertiser.py | 4 +- integrations/blender/plugin/NOTICE.md | 1 + integrations/blender/plugin/README.md | 8 + .../host/blender/opencode_link-0.4.8.zip | Bin 865343 -> 986883 bytes integrations/blender/plugin/package.json | 3 +- .../blender/plugin/scripts/host-payload.ts | 34 +- .../blender/plugin/src/console-panel.ts | 16 + integrations/blender/plugin/src/sidecar.ts | 4 + .../blender/test/console-chat.test.ts | 124 +++++ .../blender/test/console_chat_test.py | 69 +++ .../host/gaffer/opencode_link-0.3.0.zip | Bin 251901 -> 253954 bytes integrations/gaffer/plugin/package.json | 2 +- .../gaffer/plugin/scripts/build-host.ts | 2 + integrations/gaffer/plugin/src/service.ts | 92 +--- .../gaffer/plugin/src/sidecar-core.ts | 388 +--------------- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 180080 -> 181704 bytes integrations/godot/plugin/package.json | 2 +- .../godot/plugin/scripts/build-host.ts | 2 + integrations/godot/plugin/src/sidecar-core.ts | 399 +---------------- package-lock.json | 2 + packages/integration-kit/package.json | 1 + packages/integration-kit/src/panel-pipes.ts | 37 ++ packages/integration-kit/src/panel-service.ts | 96 ++++ packages/integration-kit/src/panel.ts | 422 ++++++++++++++++++ 26 files changed, 1190 insertions(+), 861 deletions(-) create mode 100644 integrations/blender/host/opencode_link/_console_opencode.py create mode 100644 integrations/blender/plugin/src/console-panel.ts create mode 100644 integrations/blender/plugin/src/sidecar.ts create mode 100644 integrations/blender/test/console-chat.test.ts create mode 100644 integrations/blender/test/console_chat_test.py create mode 100644 packages/integration-kit/src/panel-pipes.ts create mode 100644 packages/integration-kit/src/panel-service.ts create mode 100644 packages/integration-kit/src/panel.ts diff --git a/integrations/blender/host/opencode_link/_console_opencode.py b/integrations/blender/host/opencode_link/_console_opencode.py new file mode 100644 index 0000000..e282063 --- /dev/null +++ b/integrations/blender/host/opencode_link/_console_opencode.py @@ -0,0 +1,338 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Blender's OpenCode console language. Workers own the pipes; only the timer touches the UI.""" + +import json +import os +from pathlib import Path +import queue +import re +import shutil +import subprocess +import sys +import threading +import uuid + +import bpy + +from .opencode_service import registration_name + +HELP = "/connect /stop /disconnect /new /status /help /allow /reject" +INTERVAL = 0.05 + + +class Lines: + def __init__(self): + self.pending = "" + self.code = False + + def _line(self, text): + if text.lstrip().startswith(("```", "~~~")): + self.code = not self.code + return None + if self.code: + return " " + text + return re.sub(r"^\s{0,3}#{1,6}\s+", "", text).replace("**", "").replace("__", "") + + def feed(self, text, end=False): + parts = (self.pending + text).split("\n") + self.pending = parts.pop() + if end and self.pending: + parts.append(self.pending) + lines = [self._line(line.removesuffix("\r")) for line in parts] + if end: + self.pending, self.code = "", False + return [line for line in lines if line is not None] + + +class Pipes: + def __init__(self): + self.out = queue.Queue() + self.inbox = queue.Queue() + threading.Thread(target=self._read, daemon=True).start() + + def _read(self): + def failed(message): + self.out.put({"event": "exit", "data": {"message": message}}) + + node = shutil.which(os.environ.get("NEURALNOMADS_BLENDER_NODE") or "node") + if not node: + return failed("Node.js 22+ not found. Set NEURALNOMADS_BLENDER_NODE or add Node to PATH.") + script = Path(__file__).with_name("sidecar.cjs") + if not script.is_file(): + return failed("Console sidecar missing. Install the built OpenCode Link add-on.") + try: + proc = subprocess.Popen( + [node, str(script)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, encoding="utf-8", errors="replace", creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + except OSError: + return failed("Could not start Node.js.") + + def write(): + with proc.stdin: + try: + while (message := self.inbox.get()) is not None: + proc.stdin.write(json.dumps(message) + "\n") + proc.stdin.flush() + except (OSError, ValueError): + pass + + threading.Thread(target=write, daemon=True).start() + with proc.stdout: + for line in proc.stdout: + try: + self.out.put(json.loads(line)) + except ValueError: + pass + self.inbox.put(None) + proc.wait() + failed("Console sidecar exited. Use /connect to try again.") + + +class Chat: + def __init__(self): + self.pipes = None + self.lines = Lines() + self.permission = {} + self.path = "" + self.request = None + self.state, self.agent, self.model = "Disconnected", "", "" + + def send(self, method, **params): + if self.pipes is None: + self.pipes = Pipes() + request = uuid.uuid4().hex + self.pipes.inbox.put({"id": request, "channel": "blender", "method": method, "params": params}) + return request + + def close(self): + if self.pipes is not None: + self.pipes.inbox.put(None) # EOF detaches the conversation, never withdraws the offer. + self.pipes = None + self.__init__() + + def status(self): + name = os.path.basename(bpy.data.filepath) or "Untitled" + return f"OpenCode | {name} | {self.state} | agent: {self.agent or 'default'} | model: {self.model or 'default'}" + + def drain(self, append, limit=120): + if not self.pipes: + return + for _ in range(limit): + try: + item = self.pipes.out.get_nowait() + except queue.Empty: + break + self._event(item, append) + if not self.pipes: + break + + def _event(self, item, append): + name, data = item.get("event"), item.get("data", {}) + + def output(text="", end=False): + for line in self.lines.feed(text, end): + append("OUTPUT", line) + + if name == "exit": + append("ERROR", data["message"]) + self.close() + elif name == "error": + append("ERROR", data["message"]) + elif item.get("id") and self.request and item["id"] == self.request[0]: + method = self.request[1] + self.request = None + if method == "close": + self.close() + append("INFO", "Disconnected.") + elif method in ("connect", "new_session") and item.get("error"): + self.state = "Disconnected" + elif method == "prompt" and item.get("error"): + self.state = "Ready" + elif method == "interrupt" and not item.get("error"): + append("INFO", "Stop requested.") + elif self.state == "Disconnecting": + return + elif name == "disconnected": + self.state = "Disconnected" + self.permission.clear() + output(end=True) + append("ERROR", data["message"]) + elif self.state == "Disconnected": + return + elif name == "session": + self.state, self.agent, self.model = "Ready", data.get("agent"), data.get("model") + append("INFO", "Resumed conversation." if data.get("resumed") else "New conversation attached.") + append("INFO", self.status()) + elif name == "assistant_delta": + output(data["text"]) + elif name == "assistant_end": + output(end=True) + elif name == "tool": + elapsed = data.get("duration_ms") + duration = "" if elapsed is None else f" ({elapsed / 1000:.2f} s)" + append("INFO", f"Tool: {data.get('name') or 'tool'} — {data['state']}{duration}") + elif name == "status": + self.state = "Working" if data["state"] == "busy" else "Ready" + if self.state == "Ready": + output(end=True) + self.permission.clear() + if data.get("interrupted"): + append("INFO", "Interrupted.") + elif name == "agent": + self.agent = data.get("agent") + elif name == "model": + self.model = data.get("selected") + elif name == "profile": + self.agent, self.model = data.get("agent"), data.get("model") + elif name == "permission": + self.permission[data["request_id"]] = data + resources = ", ".join(data["resources"]) + append("INFO", f"Permission requested: {data['action']} {resources} — /allow once or /reject") + elif name == "permission_done": + self.permission.pop(data["request_id"], None) + + +chat = Chat() + + +def _append(kind, text): + bpy.ops.console.scrollback_append(text=text, type=kind) + + +def _broadcast(rows): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type != "CONSOLE" or area.spaces.active.language != "opencode": + continue + region = next((r for r in area.regions if r.type == "WINDOW"), None) + if region is not None: + with bpy.context.temp_override(window=window, area=area, region=region): + for kind, text in rows: + _append(kind, text) + area.tag_redraw() + + +def _drain(): + rows = [] + chat.drain(lambda kind, text: rows.append((kind, text))) + if rows: + _broadcast(rows) + return INTERVAL if chat.pipes else None + + +def disconnect(): + if chat.pipes and chat.state != "Disconnecting": + chat.state = "Disconnecting" + chat.request = (chat.send("close"), "close") + + +def check_document(): + if chat.path and chat.path != bpy.data.filepath: + disconnect() + + +def _connect(method): + from .addon import preferences, session + + path = bpy.data.filepath + if not path: + return _append("ERROR", "Save this .blend before connecting.") + host = session() + port, token, handle, label = host.snapshot() if host else (0, None, "", "") + if not token: + return _append("ERROR", "OpenCode Link is not offering this Blender yet.") + try: + registration = registration_name(preferences().service_name.strip()) + except (ValueError, AttributeError): + return _append("ERROR", "Invalid OpenCode service name in OpenCode Link preferences.") + chat.path = path + chat.state, chat.agent, chat.model = "Connecting", "", "" + chat.permission.clear() + chat.lines = Lines() + chat.request = (chat.send( + method, host="127.0.0.1", port=port, token=token, script_handle=handle, offer_label=label, + directory=os.path.dirname(path), document_name=os.path.basename(path), + document_key=os.path.normcase(os.path.abspath(path)), registration=registration, + ), method) + if not bpy.app.timers.is_registered(_drain): + bpy.app.timers.register(_drain, first_interval=0, persistent=True) + _append("INFO", "Connecting to OpenCode…") + + +def execute(context, is_interactive): + del is_interactive + history = context.space_data.history + if not history or not (text := history[-1].body.strip()): + return {"CANCELLED"} + _append("INPUT", "> " + text) + bpy.ops.console.history_append(text="", current_character=0, remove_duplicates=True) + check_document() + if text in ("/help", "/status"): + _append("INFO", HELP if text == "/help" else chat.status()) + elif text in ("/connect", "/new"): + if chat.state in ("Connecting", "Working", "Disconnecting"): + _append("INFO", "Wait for the current operation or use /stop.") + else: + _connect("connect" if text == "/connect" else "new_session") + elif text == "/disconnect": + if chat.pipes: + disconnect() + else: + _append("INFO", "Disconnected.") + elif text.startswith("/") and text not in ("/stop", "/allow", "/reject"): + _append("ERROR", "Unknown command. Use /help.") + elif chat.state not in ("Ready", "Working"): + _append("INFO", "Use /connect first.") + elif text == "/stop": + chat.request = (chat.send("interrupt"), "interrupt") + elif text in ("/allow", "/reject"): + if len(chat.permission) == 1: + request_id = next(iter(chat.permission)) + chat.send("permission_reply", request_id=request_id, reply="once" if text == "/allow" else "reject") + elif chat.permission: + _append("INFO", "Several permissions are pending; review them in OpenCode.") + else: + _append("INFO", "No permission is pending.") + elif chat.state == "Working": + _append("INFO", "OpenCode is working. Wait or use /stop.") + else: + chat.state = "Working" + chat.request = (chat.send("prompt", text=text), "prompt") + return {"FINISHED"} + + +def autocomplete(context): + return {"CANCELLED"} + + +def copy_as_script(context): + # The Console's fixed menu label says "as Script"; copy this area's visible scrollback as text. + context.window_manager.clipboard = "\n".join(line.body for line in context.space_data.scrollback) + return {"FINISHED"} + + +def banner(context): + context.space_data.prompt = "> " + _append("INFO", chat.status()) + _append("INFO", HELP) + return {"FINISHED"} + + +def register(): + # Blender 5.3 lists loaded _console_* modules (and imports them by this name on Enter). + sys.modules["_console_opencode"] = sys.modules[__name__] + + +def unregister(): + chat.close() + if bpy.app.timers.is_registered(_drain): + bpy.app.timers.unregister(_drain) + if "_console_opencode" in sys.modules: + for screen in bpy.data.screens: + for area in screen.areas: + for space in area.spaces: + if space.type == "CONSOLE" and space.language == "opencode": + space.language = "python" + space.prompt = ">>> " + sys.modules.pop("_console_opencode") diff --git a/integrations/blender/host/opencode_link/addon.py b/integrations/blender/host/opencode_link/addon.py index 73ded6f..0ff3c82 100644 --- a/integrations/blender/host/opencode_link/addon.py +++ b/integrations/blender/host/opencode_link/addon.py @@ -15,6 +15,7 @@ from . import advertiser as advertiser_module from . import console +from . import _console_opencode as chat from .blender_app import BlenderApp from .core import HostCore, require_app_version from .process import state as process_state @@ -255,6 +256,7 @@ def _on_change(*_args): def _on_save(*args): if _session is not None: _session.app.saved(args[0] if args and isinstance(args[0], str) else None) + chat.check_document() @persistent @@ -265,6 +267,7 @@ def _on_history(*_args): @persistent def _on_load(*_args): + chat.disconnect() if _session is not None: _session.app.loaded() _session.core.quarantined = False @@ -317,6 +320,7 @@ def register(): if bpy.app.background: _start_offer() else: + chat.register() bpy.app.timers.register(_start_offer, first_interval=0.1, persistent=True) @@ -331,6 +335,7 @@ def _start_offer(): def unregister(): global _session + chat.unregister() console.capture().uninstall() _remove_handlers() if _session is not None: diff --git a/integrations/blender/host/opencode_link/advertiser.py b/integrations/blender/host/opencode_link/advertiser.py index 1dd1919..4d67a56 100644 --- a/integrations/blender/host/opencode_link/advertiser.py +++ b/integrations/blender/host/opencode_link/advertiser.py @@ -42,7 +42,9 @@ def _launch_key(): def offer_label(document): name = (document or "Untitled").replace("/", " ").replace("\\", " ") name = "".join(char for char in name if ord(char) >= 32 and char != "\x7f").strip() or "Untitled" - return ("Blender: %s" % name)[:LABEL_MAX] + # Public selector for the in-app console: two Blender processes can open the same file. + suffix = " [%s]" % os.getpid() if document else "" + return ("Blender: %s" % name)[:LABEL_MAX - len(suffix)] + suffix class Advertiser(object): diff --git a/integrations/blender/plugin/NOTICE.md b/integrations/blender/plugin/NOTICE.md index 14f2baa..961698b 100644 --- a/integrations/blender/plugin/NOTICE.md +++ b/integrations/blender/plugin/NOTICE.md @@ -6,5 +6,6 @@ | The fixed programs the plugin runs inside Blender | `programs/` | GPL-3.0-or-later (SPDX header of each file; the GNU GPL version 3 text is the `LICENSE` inside the add-on archive) | | The OpenCode Link add-on, embedded as an archive | `host/blender/opencode_link-.zip` | GPL-3.0-or-later (`LICENSE` inside the archive); some handlers carry GPL-2.0-or-later headers, compatible with it | | Blender Lab's tool code, inside the add-on | `lab/` in the add-on archive | GPL-3.0-or-later, Blender Authors: copied from Blender Lab `blender_mcp` v1.0.3 (commit `2cea8d566dde07fbac28a61d698909d69724e853`), each file with its SPDX lines | +| Console chat's separate Node.js sidecar | `sidecar.cjs` in the add-on archive | MIT (integration kit and OpenCode client; bundled notices retained) | The `license` field of `package.json` is `MIT AND GPL-3.0-or-later`, as the repository's packaging rules require of a package that embeds a GPL-3.0-or-later application part: the plugin's licence and the add-on's. The programs run in Blender's Python like the add-on and share its licence. No Blender documentation is bundled: `blender_inspect` reads the running Blender and links the official documentation of its version. diff --git a/integrations/blender/plugin/README.md b/integrations/blender/plugin/README.md index 94fcdbf..1b62858 100644 --- a/integrations/blender/plugin/README.md +++ b/integrations/blender/plugin/README.md @@ -32,6 +32,14 @@ The **Plugins** section lists OpenCode for Blender as an integration: its version, whether the add-on is installed and up to date, and whether the conversation is attached; its menu installs or updates the add-on after a confirmation and detaches the conversation. **Plugins ▸ Add** also accepts the package name. +## Chat in Blender (prototype) + +With OpenCode running and OpenCode Link enabled, save your `.blend`, open a **Python Console** editor (`Shift–F4`), then choose **Console → Languages → Opencode**. Enter `/connect` to resume that file's conversation or start one, then type a message and press Enter. `/new` starts a fresh conversation, `/stop` interrupts the current turn, and `/disconnect` detaches only this conversation. Use `/status` or `/help` at any time. Node.js 22+ must be on `PATH`, or set `NEURALNOMADS_BLENDER_NODE` to its executable. The console uses the shared OpenCode service unless another service is named in the add-on preferences. + +The Console wraps lines and keeps its own Up-arrow history. An unfinished line appears when the stream finishes or the next newline arrives. **Copy as Script** copies this area's scrollback as plain text, not executable Python. Earlier messages stay in OpenCode when you reconnect; they are not replayed into Blender. `/allow` approves a single pending OpenCode permission once; `/reject` declines it. Use OpenCode to handle questions or multiple pending approvals. + +CodeNomad can stay attached separately. Blender cannot repaint or accept console input while a main-thread Python operation or bake is running. Output queues and appears once the main thread is free; `/stop` does not preempt Python already running in Blender. + ## How it works - **Discovery and consent.** While OpenCode Link is enabled, the add-on listens on `127.0.0.1` on a random port with a random 256-bit token kept in memory, and offers the session to every OpenCode service registered for your user (or to one: the add-on setting _OpenCode service_). Offers last 15 seconds and are renewed every 5 seconds. diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 03b5163a45bfcf16c61729ae106bbb803a989c75..8c1d5af23eb60dfe1a8848ec2ba1c07fb7d22af9 100644 GIT binary patch delta 118647 zcmdqKYmj8ueILesVlgC05W4_qijTWZ29`x8TLxKt6nlG=*EHhFiN}Q6!Z>f|ckt(~& zsgxAiDY+c$gY*0S|L1jY-+s-^(yo9-VEWv1&*T4oopXQtU%v9!{`MEX^VPp`^q0DC zcK+(|4}5_CKk|VOd|#kVIGTx^1Ituk2_Jf-K(v|iL~6j zQ0agBpY8v#{$_Pw^pSUaaW9@}tZ%eC-KZ1ypZwJRXZm}7{?MoTx0j@&zU8cDZP?Kax2!<5sz1ne|BbOrq-+` zNp!K%ij)2~FFpQj|NZ9PCsV+v-e}$7#HE?Y{FB7Z)e3=%<~OU&1gqnddb}DfH!(n& z9p<8L{9bqVlzXeODlL^JHrCiE&sLIdwbM=RH@a)(a_RQ%+oidv^s_(vv!z-8Qvb{U z_~6W8GgYhIjqKF@Z~p6pPxpWD!-G#Aa!v34^Zn1HC9b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At1@Z|IpPh5eC^&~ z3i@SmG1;eJ)_}4eJA3##%&>xiQ>HzmEp9I`O*w3~W0f^@jwfSPFV_;(OID#h{Ui=q zp@t21uaf33@Kh{SMBLO@3Qqr|~Z4VA{j@E(@m}+>u~a=5phOIllLIoKZvXsCX&~oOr018wqB0IXASmgkHlWyi31b zkDFCU$EUl6n7Cx8Ds#WdH`i2}T+!aJN)azkVO2AA>R>i zL(tojn8mmzlrPUE;V+svey|Z;cGyY>I&iNYO4N_~RMHj>;~Ia^o6K*&!3N zbrCvxPsLIl+@M|5mW_@h4lMj4BZ(dtxRi$h-`{EIQzIctx I*=9rk1ye{X82|tP diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index 849e5d0..ce30c92 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -47,6 +47,7 @@ } }, "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5", "esbuild": "0.28.2" }, @@ -63,7 +64,7 @@ "range": "^0.4.8", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "d5b94052efdc503c2cd3e3ff183913733b22a52d9765a5e06e03d17d5f95a01b" + "sha256": "fe3b9eb7b0648a1fc4032d4e788d1eed27970628d27dbd736f8dcc7695387133" } } } diff --git a/integrations/blender/plugin/scripts/host-payload.ts b/integrations/blender/plugin/scripts/host-payload.ts index e93cad8..0243b18 100644 --- a/integrations/blender/plugin/scripts/host-payload.ts +++ b/integrations/blender/plugin/scripts/host-payload.ts @@ -6,22 +6,15 @@ import { createHash } from "node:crypto" import { readdirSync, readFileSync } from "node:fs" import { join, relative, sep } from "node:path" import { fileURLToPath } from "node:url" +import { buildSync } from "esbuild" import { writeStoredZip } from "../src/zip.ts" export const pluginRoot = fileURLToPath(new URL("..", import.meta.url)) +const repoRoot = join(pluginRoot, "..", "..", "..") export const hostRoot = join(pluginRoot, "..", "host") export const addonRoot = join(hostRoot, "opencode_link") -export const kitServicePath = join( - pluginRoot, - "..", - "..", - "..", - "packages", - "integration-kit", - "python", - "opencode_service.py", -) +export const kitServicePath = join(repoRoot, "packages", "integration-kit", "python", "opencode_service.py") function walk(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }) @@ -50,9 +43,26 @@ export function payloadEntries(): Array<{ name: string; data: Buffer }> { .map((file) => relative(addonRoot, file).split(sep).join("/")) .filter((name) => !name.split("/").includes("__pycache__") && !name.endsWith(".pyc")) if (!files.includes("opencode_service.py")) files.push("opencode_service.py") - return files.sort().map((name) => ({ + const sidecar = buildSync({ + absWorkingDir: repoRoot, + entryPoints: [join(pluginRoot, "src", "sidecar.ts")], + preserveSymlinks: true, + bundle: true, + format: "cjs", + platform: "node", + target: "node22", + write: false, + legalComments: "eof", + }).outputFiles[0] + if (!sidecar) throw new Error("No Blender console sidecar was built") + return [...files, "sidecar.cjs"].sort().map((name) => ({ name, - data: name === "opencode_service.py" ? serviceBytes() : lf(readFileSync(join(addonRoot, name))), + data: + name === "sidecar.cjs" + ? Buffer.from(sidecar.contents) + : name === "opencode_service.py" + ? serviceBytes() + : lf(readFileSync(join(addonRoot, name))), })) } diff --git a/integrations/blender/plugin/src/console-panel.ts b/integrations/blender/plugin/src/console-panel.ts new file mode 100644 index 0000000..c70b468 --- /dev/null +++ b/integrations/blender/plugin/src/console-panel.ts @@ -0,0 +1,16 @@ +import type { PanelHost } from "../../../../packages/integration-kit/src/panel.ts" + +export const blenderPanel = { + app: "Blender", + rpcID: "neuralnomads.blender", + marker: "opencode_blender_document", + document: "document", + keyField: "document_key", + nameField: "document_name", + defaultName: "Untitled", + duplicateOffer: "Blender instances", + agent: true, + consoleEvents: true, + // Blender has no session-specific cancel/resume host methods. Interrupt the agent via OpenCode only. + hostControls: false, +} satisfies PanelHost diff --git a/integrations/blender/plugin/src/sidecar.ts b/integrations/blender/plugin/src/sidecar.ts new file mode 100644 index 0000000..989cd11 --- /dev/null +++ b/integrations/blender/plugin/src/sidecar.ts @@ -0,0 +1,4 @@ +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" +import { blenderPanel } from "./console-panel.ts" + +runPanel(blenderPanel) diff --git a/integrations/blender/test/console-chat.test.ts b/integrations/blender/test/console-chat.test.ts new file mode 100644 index 0000000..ae6ac63 --- /dev/null +++ b/integrations/blender/test/console-chat.test.ts @@ -0,0 +1,124 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { join } from "node:path" +import { it } from "node:test" +import { type Api, createPanel } from "../../../packages/integration-kit/src/panel.ts" +import { blenderPanel } from "../plugin/src/console-panel.ts" + +it("formats and fans out streamed lines in the Blender timer without bpy", () => { + const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") + const result = spawnSync(python, ["-I", join(import.meta.dirname, "console_chat_test.py")], { + encoding: "utf8", + windowsHide: true, + }) + assert.equal(result.status, 0, result.error?.message ?? result.stderr) +}) + +it("the shared sidecar binds only Blender's marked conversation and streams tools and interruption", async () => { + const calls: unknown[] = [] + const out: unknown[] = [] + const bindings = new Map([["ses_codenomad", "offer_here"]]) + const location = { directory: import.meta.dirname } + const session = { id: "ses_console", agent: "build", metadata: { [blenderPanel.marker]: "test.blend" } } + let push: (value: unknown) => void = () => {} + const api = { + rpc: (rpc: { id: string }) => { + assert.equal(rpc.id, "neuralnomads.blender") + return { + hosts: async () => ({ offers: [{ label: "Blender: test.blend [10]", offerID: "offer_here" }] }), + attachHost: async ({ offerID, sessionID }: { offerID: string; sessionID: string }) => { + bindings.set(sessionID, offerID) + return { outcome: "attached" } + }, + bindingRead: async ({ sessionID }: { sessionID: string }) => ({ + state: "attached", + binding: { offerID: bindings.get(sessionID) }, + }), + detachHost: async ({ sessionID }: { sessionID: string }) => bindings.delete(sessionID), + } + }, + session: { + list: async () => ({ data: [{ id: "ses_codenomad" }, session], cursor: {} }), + create: async () => assert.fail("Should resume the marked conversation"), + active: async () => ({}), + prompt: async (value: unknown) => calls.push(value), + interrupt: async (value: unknown) => calls.push(value), + }, + message: { list: async () => ({ data: [] }) }, + model: { list: async () => ({ data: [] }), default: async () => ({ data: { providerID: "ok", id: "model" } }) }, + event: { + subscribe: async function* ({ signal }: { signal: AbortSignal }) { + while (!signal.aborted) { + const item = await new Promise((resolve) => { + const abort = () => resolve(undefined) + signal.addEventListener("abort", abort, { once: true }) + push = (value) => { + signal.removeEventListener("abort", abort) + resolve(value) + } + }) + if (item) yield item + } + }, + }, + } as unknown as Api + + const panel = createPanel(blenderPanel, { + discover: async (registration) => { + assert.equal(registration, "service-example.json") + return api + }, + send: (event) => out.push(event), + requestHost: async (...args) => { + calls.push(args) // Blender has no session-specific host cancel/resume. + return {} + }, + }) + const call = (method: string, params?: Record) => + panel.dispatch({ method, params, id: method, channel: "blender" }) + const event = (name: string, data: object) => ({ channel: "blender", event: name, data }) + const emit = async (type: string, data: object, sessionID = session.id) => { + push({ type, data: { sessionID, ...data } }) + await new Promise((resolve) => setImmediate(resolve)) + } + + try { + await call("connect", { + ...location, + host: "127.0.0.1", + port: 4242, + token: "a".repeat(64), + script_handle: "blend-test", + offer_label: "Blender: test.blend [10]", + document_key: "test.blend", + registration: "service-example.json", + }) + assert.ok(out.some((item) => JSON.stringify(item).includes('"resumed":true'))) + assert.equal(bindings.get(session.id), "offer_here") + out.length = 0 + await call("prompt", { text: "hello" }) + await emit("session.text.delta", { delta: "not ours" }, "ses_codenomad") + await emit("session.text.delta", { delta: "hello\n" }) + await emit("session.tool.input.started", { id: "tool_1", name: "blender_context" }) + await emit("session.tool.success", { id: "tool_1" }) + await call("interrupt") + await emit("session.execution.interrupted", {}) + assert.deepEqual(out.slice(0, 3), [ + { id: "prompt", result: {} }, + event("assistant_delta", { text: "hello\n" }), + event("tool", { id: "tool_1", name: "blender_context", state: "starting" }), + ]) + const completed = out[3] as { data: { name: string; state: string; duration_ms: number } } + assert.equal(completed.data.name, "blender_context") + assert.equal(completed.data.state, "completed") + assert.ok(completed.data.duration_ms >= 0) + assert.deepEqual(out.at(-1), event("status", { state: "idle", interrupted: true })) + assert.deepEqual(calls, [ + { sessionID: session.id, text: "hello" }, + { sessionID: session.id, resume: false }, + ]) + } finally { + await panel.closeAll() + } + assert.deepEqual([...bindings], [["ses_codenomad", "offer_here"]]) +}) diff --git a/integrations/blender/test/console_chat_test.py b/integrations/blender/test/console_chat_test.py new file mode 100644 index 0000000..8ffcb8d --- /dev/null +++ b/integrations/blender/test/console_chat_test.py @@ -0,0 +1,69 @@ +"""Run without Blender: python integrations/blender/test/console_chat_test.py.""" + +from contextlib import contextmanager +from pathlib import Path +from queue import Queue +import sys +from types import SimpleNamespace as NS +import unittest + +sys.modules["bpy"] = NS() +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "host")) +from opencode_link import _console_opencode as console + + +class ConsoleTests(unittest.TestCase): + def test_lines(self): + lines = console.Lines() + self.assertEqual(lines.feed("## Heading\r\n**hel"), ["Heading"]) + self.assertEqual(lines.feed("lo**\n``"), ["hello"]) + self.assertEqual(lines.feed("`py\nx = '**'\n```\nTail"), [" x = '**'"]) + self.assertEqual(lines.feed("", end=True), ["Tail"]) + self.assertEqual(lines.feed("## prose\n"), ["prose"]) + + def test_timer_broadcasts_complete_lines_only_to_opencode_areas(self): + context = console.bpy.context = NS() + + @contextmanager + def override(**values): + context.area = values["area"] + yield + + def area(language): + result = NS(type="CONSOLE", spaces=NS(active=NS(language=language)), rows=[], + regions=[NS(type="WINDOW")], redraws=0) + result.tag_redraw = lambda: setattr(result, "redraws", result.redraws + 1) + return result + + first, second, python = area("opencode"), area("opencode"), area("python") + context.window_manager = NS(windows=[NS(screen=NS(areas=[first, python])), NS(screen=NS(areas=[second]))]) + context.temp_override = override + console.bpy.ops = NS(console=NS(scrollback_append=lambda **row: context.area.rows.append(row))) + chat = console.chat = console.Chat() + chat.pipes = NS(out=Queue(), inbox=Queue()) + chat.state = "Working" + + def add(event, **data): + chat.pipes.out.put({"event": event, "data": data}) + + add("assistant_delta", text="first\npar") + self.assertEqual(console._drain(), console.INTERVAL) + self.assertEqual(first.rows, [{"text": "first", "type": "OUTPUT"}]) + add("assistant_delta", text="tial") + add("tool", name="blender_context", state="completed", duration_ms=258) + add("assistant_end") + console._drain() + self.assertEqual(first.rows[-2:], [ + {"text": "Tool: blender_context — completed (0.26 s)", "type": "INFO"}, + {"text": "partial", "type": "OUTPUT"}, + ]) + self.assertEqual(second.rows, first.rows) + self.assertEqual(first.redraws, 2) + self.assertEqual(python.rows, []) + add("exit", message="sidecar closed") + self.assertIsNone(console._drain()) + self.assertEqual(first.rows[-1], {"text": "sidecar closed", "type": "ERROR"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index 36e588148adbec638e3bfe944b3690d520012c96..4f29a69e0c15ee47a171ec50db753c07e7950800 100644 GIT binary patch delta 2786 zcmb_eU2GIp6lVAETR<%MgIMIUG_Wh%*#Z^9l3JipC_jpTF;dFzxN~s`)C}{$%aB$e7x5?lYoK&alZb{7MK+* z{o^H=UgJwQ?}P&p`RzfNJ>JnRT5NE?>x4s-`jUjvg2{y+L7Q2m3DR3bh+uoYHz8)8 z#7AF4@KM^isa>419y3SdE$N1iRSi4zhBq441DKezt-M)C61n39 z{5-h|A=z{ieqZ9NwJw{BR@)NHE^^Y`+)VO%kyFw_wlKS7a;h=P?P3p&CrDbxPr=ty zs)3Zhor3qK1g4miYhUAja2oVzGRR%!pWQ}#DAS9izBgECl%1lP(*=D|l}bfIKde{~ zYIVoaguTh$Ls_fN(QzfCg5(J;i&o|3v+$J6_Cu5W@eE9o=eI(QoN^i_&&+P`GI^B~ zJ6A4IOH|}%{jfBWb?^5>M|5fsLP=-cl({c|3}>T#flM#pax#BD5qll#VG-k$b39(n zQ)!$QX--fhmLQmtCE~dxiFvA6lJpYqD@_bt=>7)M(n73qu}CTj|NN+eR+U@e5nl-I ze7aUyW#RdmxW&uJG=>k=vrN?L7EOJJ z8hP&`tn3SaiKb~IQmxJuc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a/integrations/gaffer/plugin/package.json +++ b/integrations/gaffer/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.3.0", "appVersions": ">=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "0ad49be2c312d3a1b8fc2980980707cd717c56ad060aaf0bbb98703141d24e5b" + "sha256": "b2219090d6e8a2c86a6d835742d03ed668d04af6525f9663a229533e24c81a7a" } } } diff --git a/integrations/gaffer/plugin/scripts/build-host.ts b/integrations/gaffer/plugin/scripts/build-host.ts index 074882f..747028a 100644 --- a/integrations/gaffer/plugin/scripts/build-host.ts +++ b/integrations/gaffer/plugin/scripts/build-host.ts @@ -13,6 +13,8 @@ const manifest = JSON.parse(readFileSync(join(host, "manifest.json"), "utf8")) if (manifest.version !== pkg.version) throw new Error("Host and plugin versions differ") const check = process.argv.includes("--check") const bundle = await build({ + absWorkingDir: join(root, "..", "..", ".."), + preserveSymlinks: true, entryPoints: [join(root, "src", "sidecar.ts")], bundle: true, format: "cjs", diff --git a/integrations/gaffer/plugin/src/service.ts b/integrations/gaffer/plugin/src/service.ts index 29aa3ef..781ec72 100644 --- a/integrations/gaffer/plugin/src/service.ts +++ b/integrations/gaffer/plugin/src/service.ts @@ -1,91 +1 @@ -import { readFile } from "node:fs/promises" -import { Agent, request } from "node:http" -import { homedir } from "node:os" -import { join } from "node:path" -import { Readable } from "node:stream" - -const agent = new Agent({ keepAlive: true, proxyEnv: {} }) - -function serviceURL(value: string) { - if (!/^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/.test(value)) - throw new Error("OpenCode service requires a literal loopback HTTP URL") - const url = new URL(value) - if (url.username || url.password || url.hash) throw new Error("Invalid OpenCode service URL") - return url -} - -// A dedicated HTTP agent bypasses environment/system proxies; redirects are never followed. -export function serviceFetch(baseUrl: string): typeof globalThis.fetch { - const origin = serviceURL(baseUrl).origin - return async (input, init) => { - const message = new Request(input, init) - if (serviceURL(message.url).origin !== origin) throw new Error("OpenCode service origin changed") - const body = message.body ? Buffer.from(await message.arrayBuffer()) : undefined - message.signal.throwIfAborted() - return new Promise((resolve, reject) => { - const req = request( - message.url, - { - agent, - method: message.method, - headers: Object.fromEntries(message.headers), - signal: message.signal, - }, - (response) => { - const status = response.statusCode ?? 500 - if (status >= 300 && status < 400) { - response.resume() - reject(new Error("OpenCode service redirect refused")) - return - } - const headers = new Headers() - for (const [key, value] of Object.entries(response.headers)) { - for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) - headers.append(key, item) - } - resolve( - new Response( - message.method === "HEAD" || [204, 205, 304].includes(status) - ? null - : (Readable.toWeb(response) as ReadableStream), - { status, headers }, - ), - ) - }, - ) - req.on("error", reject) - req.once("abort", () => reject(message.signal.reason ?? new Error("OpenCode request aborted"))) - req.end(body) - }) - } -} - -export async function discoverService( - file = join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "opencode", "service.json"), -) { - try { - const registration = JSON.parse(await readFile(file, "utf8")) - if ( - typeof registration.url !== "string" || - !Number.isInteger(registration.pid) || - registration.pid <= 0 || - typeof registration.version !== "string" || - !registration.version - ) - return undefined - const fetch = serviceFetch(registration.url) - const headers: Record = {} - if (typeof registration.password === "string") - headers.authorization = `Basic ${Buffer.from(`opencode:${registration.password}`).toString("base64")}` - const response = await fetch(`${registration.url.replace(/\/$/, "")}/api/info`, { - headers, - signal: AbortSignal.timeout(3000), - }) - if (!response.ok) return undefined - const info = await response.json() - if (info?.pid !== registration.pid || info?.version !== registration.version) return undefined - return { url: registration.url as string, headers, fetch } - } catch { - return undefined - } -} +export { discoverService, serviceFetch } from "../../../../packages/integration-kit/src/panel-service.ts" diff --git a/integrations/gaffer/plugin/src/sidecar-core.ts b/integrations/gaffer/plugin/src/sidecar-core.ts index d09aa64..44c052b 100644 --- a/integrations/gaffer/plugin/src/sidecar-core.ts +++ b/integrations/gaffer/plugin/src/sidecar-core.ts @@ -1,375 +1,19 @@ -// The in-Gaffer panel's conversations: a plain client of the OpenCode service. Gaffer offers each open script by -// itself (the installed part); the panel only attaches its own conversation to its script's offer, and never -// announces or withdraws offers. Credentials stay in this process: SDK and host errors are never forwarded. -import type { OpenCode } from "@opencode/client" -import { rpcDefinition } from "../../../../packages/integration-kit/src/contract.ts" -import { requestHost as kitRequestHost } from "../../../../packages/integration-kit/src/host-client.ts" +import { createPanel as createChat, type PanelDependencies } from "../../../../packages/integration-kit/src/panel.ts" -export type Api = ReturnType -type Rpc = Partial< - Record< - "hosts" | "attachHost" | "detachHost" | "bindingRead", - (input: object, options: object) => Promise> - > -> -type ModelRef = { id: string; providerID: string; variant?: string } -type Channel = { - id: string - directory: string - sessionID: string - label: string - offerID: string - host: { host: string; port: number; token: string } - handle: string - abort: AbortController - timer?: NodeJS.Timeout - checking: boolean - tools: Map - model?: ModelRef -} -export type PanelRequest = { id: string; channel: string; method: string; params?: Record } +export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" -// The session metadata naming the Gaffer script a conversation belongs to: Connect takes that one back. export const SCRIPT_MARKER = "opencode_gaffer_script" - -// A message of this sidecar's own, safe to show in the panel. -class PanelError extends Error {} - -// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. -export function briefly(error: unknown) { - const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") - .split(/\r?\n/)[0] - ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") - .replace(/(basic|bearer)\s+\S+/gi, "$1 …") - .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") - .slice(0, 240) - return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` -} - -const modelKey = (model: ModelRef | undefined) => - model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" - -type Part = { type?: string; text?: string; name?: string; state?: { status?: string } } -type Message = { type?: string; text?: string; content?: Part[] } -type EventData = { - sessionID?: string - delta?: string - id?: string - name?: string - action?: string - resources?: string[] - model?: ModelRef -} - -function history(messages: ReadonlyArray) { - return messages.flatMap((message) => { - if (message.type === "user") return [{ role: "user", text: message.text ?? "" }] - if (message.type !== "assistant") return [] - return (message.content ?? []).flatMap((part) => { - if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] - if (part.type === "tool") return [{ role: "tool", text: `${part.name} / ${part.state?.status ?? "unknown"}` }] - return [] - }) - }) -} - -export function createPanel(deps: { - // The running OpenCode service, or undefined when none is running (never started from here). - discover: () => Promise - send: (message: unknown) => void - requestHost?: typeof kitRequestHost - // How long Connect waits for this script's offer (Gaffer offers each script every few seconds). - offerWaitMs?: number - checkEveryMs?: number -}) { - const requestHost = deps.requestHost ?? kitRequestHost - // A Location opened for the panel loads its plugins first, which took tens of seconds in a trial. - const offerWaitMs = deps.offerWaitMs ?? 30_000 - const checkEveryMs = deps.checkEveryMs ?? 5_000 - const channels = new Map() - let client: Api | undefined - let rpc: Rpc = {} - const event = (c: { id: string }, name: string, data: object) => deps.send({ channel: c.id, event: name, data }) - const options = (c: { directory: string }) => ({ - location: { directory: c.directory }, - signal: AbortSignal.timeout(3000), - }) - const host = (c: Channel, method: "cancel" | "resume") => - requestHost(c.host, method, { script_handle: c.handle, session_id: c.sessionID }, { timeoutMs: 2000 }) - - async function api() { - if (client) return client - const found = await deps.discover() - if (!found) throw new PanelError("Start OpenCode before connecting the panel.") - client = found - rpc = found.rpc(rpcDefinition("neuralnomads.gaffer", "native") as never) as unknown as Rpc - return client - } - - // This script's offer: the one with its label among the offered hosts (offer keys stay private to the service). - async function findOffer(c: { directory: string; label: string }) { - const until = Date.now() + offerWaitMs - for (;;) { - let result: { offers?: unknown } | undefined - try { - result = (await rpc.hosts?.({}, options(c))) as typeof result - } catch (error) { - // The first call in the script's folder: OpenCode opens that Location and loads its plugins meanwhile, and - // the integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). - if ( - !/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || - Date.now() > until - ) - throw error - await new Promise((resolve) => setTimeout(resolve, 1_000)) - continue - } - const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( - (offer) => offer.label === c.label, - ) - if (offers.length > 1) - throw new PanelError(`Several scripts offer ${c.label}: attach this conversation from OpenCode (gaffer_hosts).`) - if (offers[0]) return offers[0] - if (Date.now() > until) throw new PanelError("This script is not offered to OpenCode yet; choose Connect again.") - await new Promise((resolve) => setTimeout(resolve, 1_000)) - } - } - - async function attached(c: Channel) { - const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) - return read?.state === "attached" && (read.binding as { offerID?: string } | undefined)?.offerID === c.offerID - } - - // The script's own conversation, when one is marked for it and still open. - async function markedSession(service: Api, directory: string, key: string) { - let cursor: string | undefined - for (let page = 0; page < 10; page += 1) { - const listed = await service.session.list({ directory, order: "desc", limit: 100, cursor }) - const found = listed.data.find( - (candidate) => - !candidate.time?.archived && - (candidate.metadata as Record | undefined)?.[SCRIPT_MARKER] === key, - ) - if (found) return found - cursor = listed.cursor.next ?? undefined - if (!cursor) return undefined - } - return undefined - } - - // Closing releases this panel's conversation only: the offer stays for every other conversation. - async function close(c: Channel) { - if (channels.get(c.id) === c) channels.delete(c.id) - if (c.timer) clearInterval(c.timer) - c.abort.abort() - await host(c, "cancel").catch(() => {}) - // Another client may have moved the conversation to another host: never detach that binding. - await attached(c) - .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) - .catch(() => {}) - } - - function forward(c: Channel, type: string, data: EventData) { - if (type === "session.model.selected") { - c.model = data.model - event(c, "model", { selected: modelKey(c.model) }) - } else if (type === "session.execution.started") event(c, "status", { state: "busy" }) - else if (type === "session.text.started") event(c, "assistant_start", {}) - else if (type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) - else if (type === "session.text.ended") event(c, "assistant_end", {}) - else if (type === "session.tool.input.started") { - c.tools.set(String(data.id), String(data.name ?? "tool")) - event(c, "tool", { id: data.id, name: data.name, state: "starting" }) - } else if (type === "session.tool.success" || type === "session.tool.failed") { - const name = c.tools.get(String(data.id)) - c.tools.delete(String(data.id)) - event(c, "tool", { id: data.id, name, state: type === "session.tool.success" ? "completed" : "failed" }) - } else if (type === "permission.asked") - event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources ?? [] }) - else if (type === "session.execution.succeeded" || type === "session.idle") event(c, "status", { state: "idle" }) - else if (type === "session.execution.interrupted" || type === "session.execution.failed") { - if (type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) - event(c, "status", { state: "idle" }) - void host(c, "cancel").catch(() => {}) - } - } - - async function stream(c: Channel, service: Api) { - try { - for await (const item of service.event.subscribe({ signal: c.abort.signal })) { - const data = item.data as unknown as EventData - if (data?.sessionID === c.sessionID) forward(c, item.type, data) - } - } catch { - // ended below - } - if (!c.abort.signal.aborted) event(c, "error", { message: "OpenCode disconnected; choose Connect to reconnect." }) - } - - function watch(c: Channel) { - let warned = false - c.timer = setInterval(() => { - if (c.checking) return - c.checking = true - void api() - .then(() => attached(c)) - .then((still) => { - if (!still) throw new Error("detached") - warned = false - }) - .catch(() => { - client = undefined - if (!warned) - event(c, "error", { message: "Conversation detached or service unavailable; choose Connect to reconnect." }) - warned = true - }) - .finally(() => { - c.checking = false - }) - }, checkEveryMs) - c.timer.unref?.() - } - - // A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. - const step = async (doing: string, work: () => Promise): Promise => { - try { - return await work() - } catch (error) { - if (error instanceof PanelError) throw error - throw new PanelError( - `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - ) - } - } - - async function connect(id: string, params: Record, fresh: boolean) { - const previous = channels.get(id) - if (previous) await close(previous) - if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) - throw new Error("Invalid host endpoint.") - const directory = String(params.directory ?? "") - const label = String(params.offer_label ?? "") - const key = String(params.script_key ?? "") - const handle = String(params.script_handle ?? "") - if (!directory || !label || !key || !handle) throw new Error("Incomplete connect request.") - const service = await step("reaching OpenCode", api) - // The script's conversation, unless New asked for another one. - const known = fresh - ? undefined - : await step("finding this script's conversation", () => markedSession(service, directory, key)) - const session = - known ?? - (await step("creating this script's conversation", () => - service.session.create({ - title: `Gaffer: ${String(params.script_name || "untitled")}`, - location: { directory }, - metadata: { [SCRIPT_MARKER]: key }, - }), - )) - const c: Channel = { - id, - directory, - sessionID: session.id, - label, - offerID: "", - host: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, - handle, - abort: new AbortController(), - checking: false, - tools: new Map(), - model: (session as { model?: ModelRef }).model, - } - try { - const offer = await step("finding this script's offer", () => findOffer(c)) - const result = await step("attaching the conversation to this script", async () => - rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), - ) - if (result?.outcome === "busy") - throw new PanelError("This conversation is attached to another application; detach it there first.") - if (result?.outcome !== "attached") throw new PanelError("Gaffer attachment was refused.") - c.offerID = offer.offerID - channels.set(id, c) - watch(c) - void stream(c, service) - const [messages, models, configured, active] = await step("loading the conversation", () => - Promise.all([ - service.message.list({ sessionID: c.sessionID, order: "desc", limit: 200 }), - service.model.list({ location: { directory } }), - service.model.default({ location: { directory } }), - service.session.active(), - ]), - ) - if (!c.model && configured.data) c.model = configured.data as ModelRef - event(c, "session", { id: c.sessionID, resumed: Boolean(known), model: modelKey(c.model), workspace: directory }) - event(c, "models", { - selected: modelKey(c.model), - models: models.data - .filter((model) => model.enabled) - .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), - }) - event(c, "history", { messages: history([...messages.data].reverse() as never) }) - event(c, "status", { - state: (active as Record)[c.sessionID]?.type === "running" ? "busy" : "idle", - }) - } catch (error) { - await close(c) - throw error - } - } - - async function act(c: Channel, method: string, params: Record) { - if (method === "close") return await close(c) - const service = await api() - if (method === "interrupt") { - await host(c, "cancel").catch(() => {}) - await service.session.interrupt({ sessionID: c.sessionID, resume: false }) - } else if (method === "prompt") { - if (!(await attached(c))) throw new PanelError("Gaffer was detached; choose Connect to attach again.") - await host(c, "resume") - await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) - } else if (method === "switch_model") { - const key = String(params.model ?? "") - const catalog = await service.model.list({ location: { directory: c.directory } }) - const selected = catalog.data.find((model) => model.enabled && `${model.providerID}/${model.id}` === key) - if (!selected) throw new PanelError("This model is not available in this workspace.") - c.model = { id: selected.id, providerID: selected.providerID } - await service.session.switchModel({ sessionID: c.sessionID, model: c.model }) - event(c, "model", { selected: modelKey(c.model) }) - } else if (method === "permission_reply") { - const decision = params.reply - if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") - await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) - } else throw new Error("Unknown panel action.") - } - - async function dispatch(request: PanelRequest) { - try { - const params = request.params ?? {} - if (request.method === "connect" || request.method === "new_session") - await connect(request.channel, params, request.method === "new_session") - else { - const c = channels.get(request.channel) - if (c) await act(c, request.method, params) - else if (request.method !== "close") throw new PanelError("Choose Connect first.") - } - deps.send({ id: request.id, result: {} }) - } catch (error) { - deps.send({ - channel: request.channel, - event: "error", - data: { - message: - error instanceof PanelError - ? error.message - : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - }, - }) - deps.send({ id: request.id, error: { message: "Panel action failed." } }) - } - } - - return { - dispatch, - closeAll: () => Promise.allSettled([...channels.values()].map(close)), - } -} +export const createPanel = (deps: PanelDependencies) => + createChat( + { + app: "Gaffer", + rpcID: "neuralnomads.gaffer", + marker: SCRIPT_MARKER, + document: "script", + keyField: "script_key", + nameField: "script_name", + defaultName: "untitled", + duplicateOffer: "scripts", + }, + deps, + ) diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index c34731cecbf25d1712beee0f034c693523f912c0..af4e17a033d638d476af3f75f5cd4828ecec841d 100644 GIT binary patch delta 2420 zcmbtWU2GIp6z&}U%0g8@p%i~^7gKi4Iz=QUY*|)QN>iawe#8(o-O0|~?ZE8JF!yc| zmQ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VMQdhVd`ZW ttbCUUvU;Sw-RHk)K8EIB1zTC=m9D}&vm>=HD$#ZgHq4&;B{VcN{0jv}Fs}dr delta 858 zcmah|TS!z<6rHow@r8a&mZoO6TbWRe5@n2LSteGJnwb%j&TZzZqd7P3j6q~k5J`@& z>A^N%H3p_NiqX(1Frg2_ib9y5sQ&D$2lNy4Ro(H?&_D#|Y}jkBz0cZvb7owz-+sni z@UhY4xWp9m_qQIV3tZuvbR>ztNoIG$scSW>h&CEC7Y_9oA)Buhn2Uvi@7Az!Lnt`4 zl@*3ETTR)Fo3imLB9xu81IeLm-j)YLOpwVn1y2}P_M<2+h*Gr!tGK@suGApNHL!RY z%}%0-`!C~182Q^UM=xFYLZ904oF+TanIPKbW>q?ASDGZN!&s+S6{pB6JJF1|qJSgF zR-02%9W>XC+=%%&ncO%=o^Gt5(nruoo>G+t+2W)bH?o z7Z;Wv7xMD*ghu%cJ@X=gU%HM~P-YJdw3$#wPY007i+gZ|(TAHzq4++{WcA`kxLs8ZRtnHLgtA9Y-2PqfJB~t3w4Zk4kCj--^NCs>cLS)T|-z- z`vx`hbqK|L&mA;`#TplN*EGs>Xc!4JJB+I&JPfoof|B)Ot<7$=+3N&nz0Dykk~cU6 zi()@5s}9L&Q|uzW9)USsw5YP?|BqWeitSnRQ_T_9ojvSSwTz5Yk}5Sh{)h=QEVQ%; z;^KoMy&pwx{NLl`Yww|lrTt5xQd=vlB7MA%{76x9IweazT^!ds+~q}d)KXzyKMV2Wj+&=}6J|_5Y==?PH>K{x( Hr_=og)NUs; diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json index 359f6d3..685eb8f 100644 --- a/integrations/godot/plugin/package.json +++ b/integrations/godot/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.1.0", "appVersions": ">=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "49bde399ddbaf859baae7d6686f8b4ee849ef82b15fad28fc132db9b7b0a5b2b" + "sha256": "e2d76a7f5b07363c774e399c890552dd45d74d6379661d4c16710165b6a8a3ce" } } } diff --git a/integrations/godot/plugin/scripts/build-host.ts b/integrations/godot/plugin/scripts/build-host.ts index b9b5475..5653c6b 100644 --- a/integrations/godot/plugin/scripts/build-host.ts +++ b/integrations/godot/plugin/scripts/build-host.ts @@ -18,6 +18,8 @@ const version = /^version="([^"]+)"$/m.exec(readFileSync(join(addon, "plugin.cfg if (version !== pkg.version) throw new Error("Host and plugin versions differ") const check = process.argv.includes("--check") const bundle = await build({ + absWorkingDir: join(root, "..", "..", ".."), + preserveSymlinks: true, entryPoints: [join(root, "src", "sidecar.ts")], bundle: true, format: "cjs", diff --git a/integrations/godot/plugin/src/sidecar-core.ts b/integrations/godot/plugin/src/sidecar-core.ts index 8d15e74..57699a8 100644 --- a/integrations/godot/plugin/src/sidecar-core.ts +++ b/integrations/godot/plugin/src/sidecar-core.ts @@ -1,385 +1,20 @@ -// The Godot dock's conversations: a plain client of the OpenCode service. The editor offers its project by itself -// (OpenCode Link); the dock only attaches its own conversation to that offer, and never announces or withdraws -// offers. Credentials stay in this process: SDK and host errors are never forwarded. -import type { OpenCode } from "@opencode/client" -import { rpcDefinition } from "../../../../packages/integration-kit/src/contract.ts" -import { requestHost as kitRequestHost } from "../../../../packages/integration-kit/src/host-client.ts" +import { createPanel as createChat, type PanelDependencies } from "../../../../packages/integration-kit/src/panel.ts" -export type Api = ReturnType -type Rpc = Partial< - Record< - "hosts" | "attachHost" | "detachHost" | "bindingRead", - (input: object, options: object) => Promise> - > -> -type ModelRef = { id: string; providerID: string; variant?: string } -type Channel = { - id: string - directory: string - sessionID: string - label: string - offerID: string - host: { host: string; port: number; token: string } - handle: string - abort: AbortController - timer?: NodeJS.Timeout - checking: boolean - tools: Map - model?: ModelRef -} -export type PanelRequest = { id: string; channel: string; method: string; params?: Record } +export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" -// The session metadata naming the Godot project a conversation belongs to: Connect takes that one back. export const PROJECT_MARKER = "opencode_godot_project" - -// A message of this sidecar's own, safe to show in the panel. -class PanelError extends Error {} - -// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. -export function briefly(error: unknown) { - const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") - .split(/\r?\n/)[0] - ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") - .replace(/(basic|bearer)\s+\S+/gi, "$1 …") - .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") - .slice(0, 240) - return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` -} - -const modelKey = (model: ModelRef | undefined) => - model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" - -type Part = { type?: string; text?: string; name?: string; state?: { status?: string } } -type Message = { type?: string; text?: string; content?: Part[] } -type EventData = { - sessionID?: string - delta?: string - id?: string - name?: string - action?: string - agent?: string - resources?: string[] - model?: ModelRef -} - -function history(messages: ReadonlyArray) { - return messages.flatMap((message) => { - if (message.type === "user") return [{ role: "user", text: message.text ?? "" }] - if (message.type !== "assistant") return [] - return (message.content ?? []).flatMap((part) => { - if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] - if (part.type === "tool") return [{ role: "tool", text: `${part.name} / ${part.state?.status ?? "unknown"}` }] - return [] - }) - }) -} - -export function createPanel(deps: { - // The running OpenCode service, or undefined when none is running (never started from here). - discover: () => Promise - send: (message: unknown) => void - requestHost?: typeof kitRequestHost - // How long Connect waits for this project's offer (the editor offers it every few seconds). - offerWaitMs?: number - checkEveryMs?: number -}) { - const requestHost = deps.requestHost ?? kitRequestHost - // A Location opened for the panel loads its plugins first, which took tens of seconds in a trial. - const offerWaitMs = deps.offerWaitMs ?? 30_000 - const checkEveryMs = deps.checkEveryMs ?? 5_000 - const channels = new Map() - let client: Api | undefined - let rpc: Rpc = {} - const event = (c: { id: string }, name: string, data: object) => deps.send({ channel: c.id, event: name, data }) - const options = (c: { directory: string }) => ({ - location: { directory: c.directory }, - signal: AbortSignal.timeout(3000), - }) - const host = (c: Channel, method: "cancel" | "resume") => - requestHost(c.host, method, { script_handle: c.handle, session_id: c.sessionID }, { timeoutMs: 2000 }) - - async function api() { - if (client) return client - const found = await deps.discover() - if (!found) throw new PanelError("Start OpenCode before connecting the panel.") - client = found - rpc = found.rpc(rpcDefinition("neuralnomads.godot", "native") as never) as unknown as Rpc - return client - } - - // This project's offer: the one with its label among the offered hosts (offer keys stay private to the service). - async function findOffer(c: { directory: string; label: string }) { - const until = Date.now() + offerWaitMs - for (;;) { - let result: { offers?: unknown } | undefined - try { - result = (await rpc.hosts?.({}, options(c))) as typeof result - } catch (error) { - // The first call in the project's folder: OpenCode opens that Location and loads its plugins meanwhile, and - // the integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). - if ( - !/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || - Date.now() > until - ) - throw error - await new Promise((resolve) => setTimeout(resolve, 1_000)) - continue - } - const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( - (offer) => offer.label === c.label, - ) - if (offers.length > 1) - throw new PanelError( - `Several Godot editors offer ${c.label}: attach this conversation from OpenCode (godot_hosts).`, - ) - if (offers[0]) return offers[0] - if (Date.now() > until) throw new PanelError("This project is not offered to OpenCode yet; choose Connect again.") - await new Promise((resolve) => setTimeout(resolve, 1_000)) - } - } - - async function attached(c: Channel) { - const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) - return read?.state === "attached" && (read.binding as { offerID?: string } | undefined)?.offerID === c.offerID - } - - // The project's own conversation, when one is marked for it and still open. - async function markedSession(service: Api, directory: string, key: string) { - let cursor: string | undefined - for (let page = 0; page < 10; page += 1) { - const listed = await service.session.list({ directory, order: "desc", limit: 100, cursor }) - const found = listed.data.find( - (candidate) => - !candidate.time?.archived && - (candidate.metadata as Record | undefined)?.[PROJECT_MARKER] === key, - ) - if (found) return found - cursor = listed.cursor.next ?? undefined - if (!cursor) return undefined - } - return undefined - } - - // Closing releases this panel's conversation only: the offer stays for every other conversation. - async function close(c: Channel) { - if (channels.get(c.id) === c) channels.delete(c.id) - if (c.timer) clearInterval(c.timer) - c.abort.abort() - await host(c, "cancel").catch(() => {}) - // Another client may have moved the conversation to another host: never detach that binding. - await attached(c) - .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) - .catch(() => {}) - } - - function forward(c: Channel, type: string, data: EventData) { - if (type === "session.model.selected") { - c.model = data.model - event(c, "model", { selected: modelKey(c.model) }) - } else if (type === "session.agent.selected") event(c, "agent", { agent: data.agent ?? null }) - else if (type === "session.execution.started") event(c, "status", { state: "busy" }) - else if (type === "session.text.started") event(c, "assistant_start", {}) - else if (type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) - else if (type === "session.text.ended") event(c, "assistant_end", {}) - else if (type === "session.tool.input.started") { - c.tools.set(String(data.id), String(data.name ?? "tool")) - event(c, "tool", { id: data.id, name: data.name, state: "starting" }) - } else if (type === "session.tool.success" || type === "session.tool.failed") { - const name = c.tools.get(String(data.id)) - c.tools.delete(String(data.id)) - event(c, "tool", { id: data.id, name, state: type === "session.tool.success" ? "completed" : "failed" }) - } else if (type === "permission.asked") - event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources ?? [] }) - else if (type === "session.execution.succeeded" || type === "session.idle") event(c, "status", { state: "idle" }) - else if (type === "session.execution.interrupted" || type === "session.execution.failed") { - if (type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) - event(c, "status", { state: "idle" }) - void host(c, "cancel").catch(() => {}) - } - } - - async function stream(c: Channel, service: Api) { - try { - for await (const item of service.event.subscribe({ signal: c.abort.signal })) { - const data = item.data as unknown as EventData - if (data?.sessionID === c.sessionID) forward(c, item.type, data) - } - } catch { - // ended below - } - if (!c.abort.signal.aborted) event(c, "error", { message: "OpenCode disconnected; choose Connect to reconnect." }) - } - - function watch(c: Channel) { - let warned = false - c.timer = setInterval(() => { - if (c.checking) return - c.checking = true - void api() - .then(() => attached(c)) - .then((still) => { - if (!still) throw new Error("detached") - warned = false - }) - .catch(() => { - client = undefined - if (!warned) - event(c, "error", { message: "Conversation detached or service unavailable; choose Connect to reconnect." }) - warned = true - }) - .finally(() => { - c.checking = false - }) - }, checkEveryMs) - c.timer.unref?.() - } - - // A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. - const step = async (doing: string, work: () => Promise): Promise => { - try { - return await work() - } catch (error) { - if (error instanceof PanelError) throw error - throw new PanelError( - `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - ) - } - } - - async function connect(id: string, params: Record, fresh: boolean) { - const previous = channels.get(id) - if (previous) await close(previous) - if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) - throw new Error("Invalid host endpoint.") - const directory = String(params.directory ?? "") - const label = String(params.offer_label ?? "") - const key = String(params.project_key ?? "") - const handle = String(params.script_handle ?? "") - if (!directory || !label || !key || !handle) throw new Error("Incomplete connect request.") - const service = await step("reaching OpenCode", api) - // The project's conversation, unless New asked for another one. - const known = fresh - ? undefined - : await step("finding this project's conversation", () => markedSession(service, directory, key)) - const session = - known ?? - (await step("creating this project's conversation", () => - service.session.create({ - title: `Godot: ${String(params.project_name || "project")}`, - location: { directory }, - metadata: { [PROJECT_MARKER]: key }, - }), - )) - const c: Channel = { - id, - directory, - sessionID: session.id, - label, - offerID: "", - host: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, - handle, - abort: new AbortController(), - checking: false, - tools: new Map(), - model: (session as { model?: ModelRef }).model, - } - try { - const offer = await step("finding this project's offer", () => findOffer(c)) - const result = await step("attaching the conversation to this project", async () => - rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), - ) - if (result?.outcome === "busy") - throw new PanelError("This conversation is attached to another application; detach it there first.") - if (result?.outcome !== "attached") throw new PanelError("Godot attachment was refused.") - c.offerID = offer.offerID - channels.set(id, c) - watch(c) - void stream(c, service) - const [messages, models, configured, active] = await step("loading the conversation", () => - Promise.all([ - service.message.list({ sessionID: c.sessionID, order: "desc", limit: 200 }), - service.model.list({ location: { directory } }), - service.model.default({ location: { directory } }), - service.session.active(), - ]), - ) - if (!c.model && configured.data) c.model = configured.data as ModelRef - event(c, "session", { - id: c.sessionID, - resumed: Boolean(known), - model: modelKey(c.model), - agent: (session as { agent?: string }).agent ?? null, - workspace: directory, - }) - event(c, "models", { - selected: modelKey(c.model), - models: models.data - .filter((model) => model.enabled) - .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), - }) - event(c, "history", { messages: history([...messages.data].reverse() as never) }) - event(c, "status", { - state: (active as Record)[c.sessionID]?.type === "running" ? "busy" : "idle", - }) - } catch (error) { - await close(c) - throw error - } - } - - async function act(c: Channel, method: string, params: Record) { - if (method === "close") return await close(c) - const service = await api() - if (method === "interrupt") { - await host(c, "cancel").catch(() => {}) - await service.session.interrupt({ sessionID: c.sessionID, resume: false }) - } else if (method === "prompt") { - if (!(await attached(c))) throw new PanelError("Godot was detached; choose Connect to attach again.") - await host(c, "resume") - await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) - } else if (method === "switch_model") { - const key = String(params.model ?? "") - const catalog = await service.model.list({ location: { directory: c.directory } }) - const selected = catalog.data.find((model) => model.enabled && `${model.providerID}/${model.id}` === key) - if (!selected) throw new PanelError("This model is not available in this workspace.") - c.model = { id: selected.id, providerID: selected.providerID } - await service.session.switchModel({ sessionID: c.sessionID, model: c.model }) - event(c, "model", { selected: modelKey(c.model) }) - } else if (method === "permission_reply") { - const decision = params.reply - if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") - await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) - } else throw new Error("Unknown panel action.") - } - - async function dispatch(request: PanelRequest) { - try { - const params = request.params ?? {} - if (request.method === "connect" || request.method === "new_session") - await connect(request.channel, params, request.method === "new_session") - else { - const c = channels.get(request.channel) - if (c) await act(c, request.method, params) - else if (request.method !== "close") throw new PanelError("Choose Connect first.") - } - deps.send({ id: request.id, result: {} }) - } catch (error) { - deps.send({ - channel: request.channel, - event: "error", - data: { - message: - error instanceof PanelError - ? error.message - : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - }, - }) - deps.send({ id: request.id, error: { message: "Panel action failed." } }) - } - } - - return { - dispatch, - closeAll: () => Promise.allSettled([...channels.values()].map(close)), - } -} +export const createPanel = (deps: PanelDependencies) => + createChat( + { + app: "Godot", + rpcID: "neuralnomads.godot", + marker: PROJECT_MARKER, + document: "project", + keyField: "project_key", + nameField: "project_name", + defaultName: "project", + duplicateOffer: "Godot editors", + agent: true, + }, + deps, + ) diff --git a/package-lock.json b/package-lock.json index 4099357..4786feb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,6 +42,7 @@ "version": "0.4.8", "license": "MIT AND GPL-3.0-or-later", "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5", "esbuild": "0.28.2" }, @@ -4871,6 +4872,7 @@ "semver": "7.8.5" }, "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5" }, "peerDependencies": { diff --git a/packages/integration-kit/package.json b/packages/integration-kit/package.json index 78dda26..f1c910f 100644 --- a/packages/integration-kit/package.json +++ b/packages/integration-kit/package.json @@ -26,6 +26,7 @@ } }, "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5" }, "dependencies": { diff --git a/packages/integration-kit/src/panel-pipes.ts b/packages/integration-kit/src/panel-pipes.ts new file mode 100644 index 0000000..c92d327 --- /dev/null +++ b/packages/integration-kit/src/panel-pipes.ts @@ -0,0 +1,37 @@ +import readline from "node:readline" +import { OpenCode } from "@opencode/client" +import { createPanel, type PanelHost, type PanelRequest } from "./panel.ts" +import { discoverService } from "./panel-service.ts" + +export function runPanel(config: PanelHost) { + const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) + const panel = createPanel(config, { + send, + discover: async (registration) => { + const endpoint = await discoverService(undefined, registration) + return endpoint && OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers, fetch: endpoint.fetch }) + }, + }) + const queues = new Map>() + const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) + input.on("line", (line) => { + if (!line.trim()) return + try { + if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") + const request = JSON.parse(line) as PanelRequest + if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") + const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => panel.dispatch(request)) + queues.set(request.channel, next) + void next.finally(() => { + if (queues.get(request.channel) === next) queues.delete(request.channel) + }) + } catch { + send({ error: { message: "Invalid panel request." } }) + } + }) + input.on("close", () => { + void Promise.allSettled(queues.values()) + .then(panel.closeAll) + .finally(() => process.exit(0)) + }) +} diff --git a/packages/integration-kit/src/panel-service.ts b/packages/integration-kit/src/panel-service.ts new file mode 100644 index 0000000..8a6f8d1 --- /dev/null +++ b/packages/integration-kit/src/panel-service.ts @@ -0,0 +1,96 @@ +import { readFile } from "node:fs/promises" +import { Agent, request } from "node:http" +import { homedir } from "node:os" +import { dirname, join } from "node:path" +import { Readable } from "node:stream" + +const agent = new Agent({ keepAlive: true, proxyEnv: {} }) + +function serviceURL(value: string) { + if (!/^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/.test(value)) + throw new Error("OpenCode service requires a literal loopback HTTP URL") + const url = new URL(value) + if (url.username || url.password || url.hash) throw new Error("Invalid OpenCode service URL") + return url +} + +// A dedicated HTTP agent bypasses environment/system proxies; redirects are never followed. +export function serviceFetch(baseUrl: string): typeof globalThis.fetch { + const origin = serviceURL(baseUrl).origin + return async (input, init) => { + const message = new Request(input, init) + if (serviceURL(message.url).origin !== origin) throw new Error("OpenCode service origin changed") + const body = message.body ? Buffer.from(await message.arrayBuffer()) : undefined + message.signal.throwIfAborted() + return new Promise((resolve, reject) => { + const req = request( + message.url, + { + agent, + method: message.method, + headers: Object.fromEntries(message.headers), + signal: message.signal, + }, + (response) => { + const status = response.statusCode ?? 500 + if (status >= 300 && status < 400) { + response.resume() + reject(new Error("OpenCode service redirect refused")) + return + } + const headers = new Headers() + for (const [key, value] of Object.entries(response.headers)) { + for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) + headers.append(key, item) + } + resolve( + new Response( + message.method === "HEAD" || [204, 205, 304].includes(status) + ? null + : (Readable.toWeb(response) as ReadableStream), + { status, headers }, + ), + ) + }, + ) + req.on("error", reject) + req.once("abort", () => reject(message.signal.reason ?? new Error("OpenCode request aborted"))) + req.end(body) + }) + } +} + +export async function discoverService( + file = join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "opencode", "service.json"), + registrationFile?: string, +) { + try { + if (registrationFile) { + if (!/^service(?:-[A-Za-z0-9._-]{1,64})?\.json$/.test(registrationFile)) return undefined + file = join(dirname(file), registrationFile) + } + const registration = JSON.parse(await readFile(file, "utf8")) + if ( + typeof registration.url !== "string" || + !Number.isInteger(registration.pid) || + registration.pid <= 0 || + typeof registration.version !== "string" || + !registration.version + ) + return undefined + const fetch = serviceFetch(registration.url) + const headers: Record = {} + if (typeof registration.password === "string") + headers.authorization = `Basic ${Buffer.from(`opencode:${registration.password}`).toString("base64")}` + const response = await fetch(`${registration.url.replace(/\/$/, "")}/api/info`, { + headers, + signal: AbortSignal.timeout(3000), + }) + if (!response.ok) return undefined + const info = await response.json() + if (info?.pid !== registration.pid || info?.version !== registration.version) return undefined + return { url: registration.url as string, headers, fetch } + } catch { + return undefined + } +} diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts new file mode 100644 index 0000000..a351bda --- /dev/null +++ b/packages/integration-kit/src/panel.ts @@ -0,0 +1,422 @@ +// An in-app chat is a plain client: attach its conversation to the host's existing offer, never announce one. +import type { OpenCode } from "@opencode/client" +import { rpcDefinition } from "./contract.ts" +import { requestHost as kitRequestHost } from "./host-client.ts" + +export type Api = ReturnType +type Rpc = Partial< + Record< + "hosts" | "attachHost" | "detachHost" | "bindingRead", + (input: object, options: object) => Promise> + > +> +type ModelRef = { id: string; providerID: string; variant?: string } +type Channel = { + id: string + directory: string + sessionID: string + label: string + offerID: string + host: { host: string; port: number; token: string } + handle: string + abort: AbortController + timer?: NodeJS.Timeout + checking: boolean + tools: Map + model?: ModelRef +} +export type PanelRequest = { id: string; channel: string; method: string; params?: Record } + +export type PanelHost = { + app: string + rpcID: string + marker: string + document: string + keyField: string + nameField: string + defaultName: string + duplicateOffer: string + agent?: boolean + consoleEvents?: boolean + hostControls?: false +} +export type PanelDependencies = { + // The running OpenCode service, or undefined when none is running (never started from here). + discover: (registration?: string) => Promise + send: (message: unknown) => void + requestHost?: typeof kitRequestHost + offerWaitMs?: number + checkEveryMs?: number +} + +// A message of this sidecar's own, safe to show in the panel. +class PanelError extends Error {} + +// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. +export function briefly(error: unknown) { + const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") + .split(/\r?\n/)[0] + ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") + .replace(/(basic|bearer)\s+\S+/gi, "$1 …") + .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") + .slice(0, 240) + return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` +} + +const modelKey = (model: ModelRef | undefined) => + model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" + +type Part = { type?: string; text?: string; name?: string; state?: { status?: string } } +type Message = { type?: string; text?: string; content?: Part[] } +type EventData = { + sessionID?: string + delta?: string + id?: string + name?: string + action?: string + agent?: string + requestID?: string + resources?: string[] + model?: ModelRef +} + +function history(messages: ReadonlyArray) { + return messages.flatMap((message) => { + if (message.type === "user") return [{ role: "user", text: message.text ?? "" }] + if (message.type !== "assistant") return [] + return (message.content ?? []).flatMap((part) => { + if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] + if (part.type === "tool") return [{ role: "tool", text: `${part.name} / ${part.state?.status ?? "unknown"}` }] + return [] + }) + }) +} + +export function createPanel(config: PanelHost, deps: PanelDependencies) { + const requestHost = deps.requestHost ?? kitRequestHost + // A Location opened for the panel loads its plugins first, which took tens of seconds in a trial. + const offerWaitMs = deps.offerWaitMs ?? 30_000 + const checkEveryMs = deps.checkEveryMs ?? 5_000 + const channels = new Map() + let client: Api | undefined + let registration: string | undefined + let rpc: Rpc = {} + const event = (c: { id: string }, name: string, data: object) => deps.send({ channel: c.id, event: name, data }) + const options = (c: { directory: string }) => ({ + location: { directory: c.directory }, + signal: AbortSignal.timeout(3000), + }) + const host = (c: Channel, method: "cancel" | "resume") => + config.hostControls === false + ? Promise.resolve() + : requestHost(c.host, method, { script_handle: c.handle, session_id: c.sessionID }, { timeoutMs: 2000 }) + + async function api() { + if (client) return client + const found = await deps.discover(registration) + if (!found) throw new PanelError("Start OpenCode before connecting the panel.") + client = found + rpc = found.rpc(rpcDefinition(config.rpcID, "native") as never) as unknown as Rpc + return client + } + + // This project's offer: the one with its label among the offered hosts (offer keys stay private to the service). + async function findOffer(c: { directory: string; label: string }) { + const until = Date.now() + offerWaitMs + for (;;) { + let result: { offers?: unknown } | undefined + try { + result = (await rpc.hosts?.({}, options(c))) as typeof result + } catch (error) { + // The first call in the project's folder: OpenCode opens that Location and loads its plugins meanwhile, and + // the integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). + if ( + !/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || + Date.now() > until + ) + throw error + await new Promise((resolve) => setTimeout(resolve, 1_000)) + continue + } + const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( + (offer) => offer.label === c.label, + ) + if (offers.length > 1) + throw new PanelError( + `Several ${config.duplicateOffer} offer ${c.label}: attach this conversation from OpenCode (${config.app.toLowerCase()}_hosts).`, + ) + if (offers[0]) return offers[0] + if (Date.now() > until) + throw new PanelError(`This ${config.document} is not offered to OpenCode yet; choose Connect again.`) + await new Promise((resolve) => setTimeout(resolve, 1_000)) + } + } + + async function attached(c: Channel) { + const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) + return read?.state === "attached" && (read.binding as { offerID?: string } | undefined)?.offerID === c.offerID + } + + // The project's own conversation, when one is marked for it and still open. + async function markedSession(service: Api, directory: string, key: string) { + let cursor: string | undefined + for (let page = 0; page < 10; page += 1) { + const listed = await service.session.list({ directory, order: "desc", limit: 100, cursor }) + const found = listed.data.find( + (candidate) => + !candidate.time?.archived && + (candidate.metadata as Record | undefined)?.[config.marker] === key, + ) + if (found) return found + cursor = listed.cursor.next ?? undefined + if (!cursor) return undefined + } + return undefined + } + + // Closing releases this panel's conversation only: the offer stays for every other conversation. + async function close(c: Channel) { + if (channels.get(c.id) === c) channels.delete(c.id) + if (c.timer) clearInterval(c.timer) + c.abort.abort() + await host(c, "cancel").catch(() => {}) + // Another client may have moved the conversation to another host: never detach that binding. + await attached(c) + .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) + .catch(() => {}) + } + + function forward(c: Channel, type: string, data: EventData) { + if (type === "session.model.selected") { + c.model = data.model + event(c, "model", { selected: modelKey(c.model) }) + } else if (config.agent && type === "session.agent.selected") event(c, "agent", { agent: data.agent ?? null }) + else if (config.consoleEvents && type === "session.step.started") { + c.model = data.model + event(c, "profile", { agent: data.agent, model: modelKey(c.model) }) + } else if (type === "session.execution.started") event(c, "status", { state: "busy" }) + else if (type === "session.text.started") event(c, "assistant_start", {}) + else if (type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) + else if (type === "session.text.ended") event(c, "assistant_end", {}) + else if (type === "session.tool.input.started") { + c.tools.set(String(data.id), { name: String(data.name ?? "tool"), started: performance.now() }) + event(c, "tool", { id: data.id, name: data.name, state: "starting" }) + } else if (type === "session.tool.success" || type === "session.tool.failed") { + const tool = c.tools.get(String(data.id)) + c.tools.delete(String(data.id)) + event(c, "tool", { + id: data.id, + name: tool?.name, + state: type === "session.tool.success" ? "completed" : "failed", + ...(config.consoleEvents && tool ? { duration_ms: Math.round(performance.now() - tool.started) } : {}), + }) + } else if (type === "permission.asked") + event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources ?? [] }) + else if (config.consoleEvents && type === "permission.replied") + event(c, "permission_done", { request_id: data.requestID }) + else if (type === "session.execution.succeeded" || type === "session.idle") event(c, "status", { state: "idle" }) + else if (type === "session.execution.interrupted" || type === "session.execution.failed") { + if (type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) + event(c, "status", { + state: "idle", + ...(config.consoleEvents && type === "session.execution.interrupted" ? { interrupted: true } : {}), + }) + void host(c, "cancel").catch(() => {}) + } + } + + async function stream(c: Channel, service: Api) { + try { + for await (const item of service.event.subscribe({ signal: c.abort.signal })) { + const data = item.data as unknown as EventData + if (data?.sessionID === c.sessionID) forward(c, item.type, data) + } + } catch { + // ended below + } + if (!c.abort.signal.aborted) + event(c, config.consoleEvents ? "disconnected" : "error", { + message: "OpenCode disconnected; choose Connect to reconnect.", + }) + } + + function watch(c: Channel) { + let warned = false + c.timer = setInterval(() => { + if (c.checking) return + c.checking = true + void api() + .then(() => attached(c)) + .then((still) => { + if (!still) throw new Error("detached") + warned = false + }) + .catch(() => { + client = undefined + if (!warned && channels.get(c.id) === c) + event(c, config.consoleEvents ? "disconnected" : "error", { + message: "Conversation detached or service unavailable; choose Connect to reconnect.", + }) + warned = true + }) + .finally(() => { + c.checking = false + }) + }, checkEveryMs) + c.timer.unref?.() + } + + // A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. + const step = async (doing: string, work: () => Promise): Promise => { + try { + return await work() + } catch (error) { + if (error instanceof PanelError) throw error + throw new PanelError( + `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, + ) + } + } + + async function connect(id: string, params: Record, fresh: boolean) { + const previous = channels.get(id) + if (previous) await close(previous) + if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) + throw new Error("Invalid host endpoint.") + const directory = String(params.directory ?? "") + const label = String(params.offer_label ?? "") + const key = String(params[config.keyField] ?? "") + const handle = String(params.script_handle ?? "") + if (!directory || !label || !key || !handle) throw new Error("Incomplete connect request.") + if (config.hostControls === false) { + const next = typeof params.registration === "string" ? params.registration : undefined + if (next !== registration) client = undefined + registration = next + } + const service = await step("reaching OpenCode", api) + // The project's conversation, unless New asked for another one. + const known = fresh + ? undefined + : await step(`finding this ${config.document}'s conversation`, () => markedSession(service, directory, key)) + const session = + known ?? + (await step(`creating this ${config.document}'s conversation`, () => + service.session.create({ + title: `${config.app}: ${String(params[config.nameField] || config.defaultName)}`, + location: { directory }, + metadata: { [config.marker]: key }, + }), + )) + const c: Channel = { + id, + directory, + sessionID: session.id, + label, + offerID: "", + host: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, + handle, + abort: new AbortController(), + checking: false, + tools: new Map(), + model: (session as { model?: ModelRef }).model, + } + try { + const offer = await step(`finding this ${config.document}'s offer`, () => findOffer(c)) + const result = await step(`attaching the conversation to this ${config.document}`, async () => + rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), + ) + if (result?.outcome === "busy") + throw new PanelError("This conversation is attached to another application; detach it there first.") + if (result?.outcome !== "attached") throw new PanelError(`${config.app} attachment was refused.`) + c.offerID = offer.offerID + channels.set(id, c) + watch(c) + void stream(c, service) + const [messages, models, configured, active] = await step("loading the conversation", () => + Promise.all([ + service.message.list({ sessionID: c.sessionID, order: "desc", limit: 200 }), + service.model.list({ location: { directory } }), + service.model.default({ location: { directory } }), + service.session.active(), + ]), + ) + if (!c.model && configured.data) c.model = configured.data as ModelRef + event(c, "session", { + id: c.sessionID, + resumed: Boolean(known), + model: modelKey(c.model), + ...(config.agent ? { agent: (session as { agent?: string }).agent ?? null } : {}), + workspace: directory, + }) + event(c, "models", { + selected: modelKey(c.model), + models: models.data + .filter((model) => model.enabled) + .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), + }) + event(c, "history", { messages: history([...messages.data].reverse() as never) }) + event(c, "status", { + state: (active as Record)[c.sessionID]?.type === "running" ? "busy" : "idle", + }) + } catch (error) { + await close(c) + throw error + } + } + + async function act(c: Channel, method: string, params: Record) { + if (method === "close") return await close(c) + const service = await api() + if (method === "interrupt") { + await host(c, "cancel").catch(() => {}) + await service.session.interrupt({ sessionID: c.sessionID, resume: false }) + } else if (method === "prompt") { + if (!(await attached(c))) throw new PanelError(`${config.app} was detached; choose Connect to attach again.`) + await host(c, "resume") + await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) + } else if (method === "switch_model") { + const key = String(params.model ?? "") + const catalog = await service.model.list({ location: { directory: c.directory } }) + const selected = catalog.data.find((model) => model.enabled && `${model.providerID}/${model.id}` === key) + if (!selected) throw new PanelError("This model is not available in this workspace.") + c.model = { id: selected.id, providerID: selected.providerID } + await service.session.switchModel({ sessionID: c.sessionID, model: c.model }) + event(c, "model", { selected: modelKey(c.model) }) + } else if (method === "permission_reply") { + const decision = params.reply + if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") + await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) + } else throw new Error("Unknown panel action.") + } + + async function dispatch(request: PanelRequest) { + try { + const params = request.params ?? {} + if (request.method === "connect" || request.method === "new_session") + await connect(request.channel, params, request.method === "new_session") + else { + const c = channels.get(request.channel) + if (c) await act(c, request.method, params) + else if (request.method !== "close") throw new PanelError("Choose Connect first.") + } + deps.send({ id: request.id, result: {} }) + } catch (error) { + deps.send({ + channel: request.channel, + event: "error", + data: { + message: + error instanceof PanelError + ? error.message + : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, + }, + }) + deps.send({ id: request.id, error: { message: "Panel action failed." } }) + } + } + + return { + dispatch, + closeAll: () => Promise.allSettled([...channels.values()].map(close)), + } +} From 902193766f1e12e9f5f2843fa8e567402094383b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 19 Nov 2026 23:23:26 +0100 Subject: [PATCH 02/13] refactor: use the same sidecar runner in all three hosts --- integrations/blender/plugin/NOTICE.md | 2 +- .../host/blender/opencode_link-0.4.8.zip | Bin 986883 -> 986952 bytes integrations/blender/plugin/package.json | 2 +- .../host/gaffer/opencode_link-0.3.0.zip | Bin 253954 -> 253647 bytes integrations/gaffer/plugin/package.json | 2 +- .../gaffer/plugin/src/sidecar-core.ts | 31 +++--- integrations/gaffer/plugin/src/sidecar.ts | 37 +------ .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 181704 -> 181643 bytes integrations/godot/plugin/package.json | 2 +- integrations/godot/plugin/src/service.ts | 91 ------------------ integrations/godot/plugin/src/sidecar-core.ts | 33 ++++--- integrations/godot/plugin/src/sidecar.ts | 37 +------ packages/integration-kit/src/panel-pipes.ts | 6 +- 13 files changed, 46 insertions(+), 197 deletions(-) delete mode 100644 integrations/godot/plugin/src/service.ts diff --git a/integrations/blender/plugin/NOTICE.md b/integrations/blender/plugin/NOTICE.md index 961698b..5f2bd2f 100644 --- a/integrations/blender/plugin/NOTICE.md +++ b/integrations/blender/plugin/NOTICE.md @@ -6,6 +6,6 @@ | The fixed programs the plugin runs inside Blender | `programs/` | GPL-3.0-or-later (SPDX header of each file; the GNU GPL version 3 text is the `LICENSE` inside the add-on archive) | | The OpenCode Link add-on, embedded as an archive | `host/blender/opencode_link-.zip` | GPL-3.0-or-later (`LICENSE` inside the archive); some handlers carry GPL-2.0-or-later headers, compatible with it | | Blender Lab's tool code, inside the add-on | `lab/` in the add-on archive | GPL-3.0-or-later, Blender Authors: copied from Blender Lab `blender_mcp` v1.0.3 (commit `2cea8d566dde07fbac28a61d698909d69724e853`), each file with its SPDX lines | -| Console chat's separate Node.js sidecar | `sidecar.cjs` in the add-on archive | MIT (integration kit and OpenCode client; bundled notices retained) | +| Console chat's separate Node.js sidecar | `sidecar.cjs` in the add-on archive | MIT (integration kit and OpenCode client; bundled notices retained) | The `license` field of `package.json` is `MIT AND GPL-3.0-or-later`, as the repository's packaging rules require of a package that embeds a GPL-3.0-or-later application part: the plugin's licence and the add-on's. The programs run in Blender's Python like the add-on and share its licence. No Blender documentation is bundled: `blender_inspect` reads the running Blender and links the official documentation of its version. diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 8c1d5af23eb60dfe1a8848ec2ba1c07fb7d22af9..0040c8b7311059830fd229456761bfe6cd8c6243 100644 GIT binary patch delta 209 zcmZpkXLDknO+yP~3sVbo3rh=Y3tJ0&3r7p*7OwR_I6Idy$JVW2WT_Doj_%<`HGIpI$wW$5KVXN}(VzFEvLGEbW++qoHZdr2qtF z`I#wDJ?&fO@c=RJ_AT@H%<>UdO#jTw@5Sgb-Hwmnl;gm09)^;P%)F_A{KC`w`1qw5 p%crm8`QtS5O(?&C13A1a?5UT7ZF}{U0BY2LP1xM1=qV delta 177 zcmX>x&!%~vO+yP~3sVbo3rh=Y3tJ0&3r7p*7OwR_IOo3mVPm<1k-@Tk#}BUUJAQEQ zU&>OJpP4d!&O9E=_Mh{3fS7mt&v|@i`3SYsE%^AoIG7jmFq9+~XHOSo;uo1dkB?u9 zqxv{dC?hj(`osTx!qZy=_yo8a;J|45J3f9(#j{WO7|Jt?QuPWd1H4(;K+<+VxLSaL K!Ra3#kOu%;Wjd?? diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index ce30c92..455ef68 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.4.8", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "fe3b9eb7b0648a1fc4032d4e788d1eed27970628d27dbd736f8dcc7695387133" + "sha256": "491b63857e2856d9fa680c6a6db562c60dbc6d4bf4d74e708465cc9c2be704d1" } } } diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_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v;a}mWI>e(U=ICp|Xzy3p@#~=AAFtgZh*VM%wNsU@ijfc9RZaJn z0f8Iz^X%9CT@zd|NCa58%XN)gml>MiDEQP3+LY#^TY~F zi4f9*S!U-WX&mutgpe&P1=Mzei^rLfLJoJev;EYGqJK&$m%^>82Zm@ynG|eD-$VSU!o`pBP9B#K5gtWk; z2G-A2gOKTtR4FqF!N|m)@`OVjqb%tq{KIXzIjplNrlE-2I^%ZEq_7ojO%c1)i`-=!u+AuCtMZ{yY@!Df@K!48m19QQ430vCXbk#N zS*zL?fN*S-!~42yVc^*~wH)1WNII)?M7mITaYwdD!1?JSih$Fwy&E>GzgyCUoRKlU z{R%U%BSXlM0f~Q^?hAr{W;3RON|IKEr4&5Kymd{N^3}#$vQ^RK>u+56Q-&hAwdFX| z0ig+-GsOZzPQJ?(ZW{W}P}3meH0P&3Ww8RNcaZ%E>m;KmFSQfZXl(06qsFYBLe`*s zm%fx{%;lJ3@&Bjgt$DV{i2jh8;u1Wj3Y z4D(Gw4zH$|1SkAp{l%r5CK@EulfjhbLDW)44I&_M)WD-`n4|L8)mcxw^EmX80m{!e zFZLF*>5Pn_4>k zQ6ZzeR4CM8w@U^)^5lA4RwUx+09!p_h`=jFY%)ZH%oV&ISIkSL#SDZxh7@eb6och> zZ~~oSMn;ur2EJBX`i}?r8r6*(wIyd?kx#!#w+(3O7YyyI`ia5}{#c}Udk;F7k^3Om@Wp4xEbzuyt)4Aoda= z%wAim2*Y;=O3Hkf22v2B4K`X`l~YQef%cw)B-$ch&A(Tu_h# zHTZnf?y?PIrgB%39!c+nqTklj62|Yur_Xh%#zfNgC)lAtqtha_Ed_Pms2*o)8wC zcv8&3_fCo&{O+Vsz-~kHNs)ntpNYbFiH&$u=)}KSeQOo-gW*C=b_tUdM?S#7G!+7Mm{!Q`pMS#eMhP_kSy+Qi1>g diff --git a/integrations/gaffer/plugin/package.json b/integrations/gaffer/plugin/package.json index dc57ff7..4d22cf6 100644 --- a/integrations/gaffer/plugin/package.json +++ b/integrations/gaffer/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.3.0", "appVersions": ">=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "b2219090d6e8a2c86a6d835742d03ed668d04af6525f9663a229533e24c81a7a" + "sha256": "53db2a63cc4b1b7665bfc9b32362cc064b148f840d19980391bcf40feba589fc" } } } diff --git a/integrations/gaffer/plugin/src/sidecar-core.ts b/integrations/gaffer/plugin/src/sidecar-core.ts index 44c052b..2f07d80 100644 --- a/integrations/gaffer/plugin/src/sidecar-core.ts +++ b/integrations/gaffer/plugin/src/sidecar-core.ts @@ -1,19 +1,20 @@ -import { createPanel as createChat, type PanelDependencies } from "../../../../packages/integration-kit/src/panel.ts" +import { + createPanel as createChat, + type PanelDependencies, + type PanelHost, +} from "../../../../packages/integration-kit/src/panel.ts" export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" export const SCRIPT_MARKER = "opencode_gaffer_script" -export const createPanel = (deps: PanelDependencies) => - createChat( - { - app: "Gaffer", - rpcID: "neuralnomads.gaffer", - marker: SCRIPT_MARKER, - document: "script", - keyField: "script_key", - nameField: "script_name", - defaultName: "untitled", - duplicateOffer: "scripts", - }, - deps, - ) +export const panelHost = { + app: "Gaffer", + rpcID: "neuralnomads.gaffer", + marker: SCRIPT_MARKER, + document: "script", + keyField: "script_key", + nameField: "script_name", + defaultName: "untitled", + duplicateOffer: "scripts", +} satisfies PanelHost +export const createPanel = (deps: PanelDependencies) => createChat(panelHost, deps) diff --git a/integrations/gaffer/plugin/src/sidecar.ts b/integrations/gaffer/plugin/src/sidecar.ts index 2764498..535b9cc 100644 --- a/integrations/gaffer/plugin/src/sidecar.ts +++ b/integrations/gaffer/plugin/src/sidecar.ts @@ -1,35 +1,4 @@ -// The in-Gaffer panel's private JSONL client, built into the installed part as sidecar.cjs and run by Node. -import readline from "node:readline" -import { OpenCode } from "@opencode/client" -import { discoverService } from "./service.ts" -import { createPanel, type PanelRequest } from "./sidecar-core.ts" +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" +import { panelHost } from "./sidecar-core.ts" -const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) -const panel = createPanel({ - send, - discover: async () => { - const endpoint = await discoverService() - return endpoint && OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers, fetch: endpoint.fetch }) - }, -}) -const queues = new Map>() - -const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) -input.on("line", (line) => { - if (!line.trim()) return - try { - if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") - const request = JSON.parse(line) as PanelRequest - if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") - const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => panel.dispatch(request)) - queues.set(request.channel, next) - void next.finally(() => { - if (queues.get(request.channel) === next) queues.delete(request.channel) - }) - } catch { - send({ error: { message: "Invalid panel request." } }) - } -}) -input.on("close", () => { - void panel.closeAll().finally(() => process.exit(0)) -}) +runPanel(panelHost) diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index af4e17a033d638d476af3f75f5cd4828ecec841d..01d8ec947a1f95bd782bd8e4502bf01e58af5be2 100644 GIT binary patch delta 7456 zcma)B3v^V~x%S@@0uz#e1PBR`lL?8LkW6@~5QMhMAKvlFWpe2@)}Y zv_dP06ePb_5D}k%AU-ZpdBWbd>0 zzyHVgKXY_d!m3pX%U-5!X^CgPtuFrh8M;RPZ>;x}r#7ERqh~tso@t_QLY*gI))dtF z>&$TTBN_Bk9@C%b7u+^(f4VxwOgWlUcfpX>Ew5HRzppIcH zj*m{H^p0*%wHb);q0@9dFDRo_E_I5Vxut;yHeD~e@YYGxhwr^aB|N$eSGtx`mLi`} zUGFb4a{Yn2`iT9#BO8+`r&p!3Cg}A<{K0^8X1?L~6&d>2?8&sAFHHlj;xZ~^PlCwg zwPlpVkCo9Q_J??WU<$b;FFE}F6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>@l*)qwI5l7>M=HKrq$4BV<}5 zQ*Y+pk#triABV!&*Zcb*Ou@yB-adDv7f9`C=;DJWuh}y+DdOCb!j}W&kLt~Bj~FfX z%6{7$)5MFuU$Z<9=Za4Q@e7;8z_-Od_gt>>Ia zoayJ8`LIYBdS7;iaY~LcU2YoHU&b^lj8ly+x3kLZu5v1+)2()!;_dTzURWt!D3EuV za?DP}qzHpQB4oMKEbRU9tHsM|;<+$w&P!!gmA^02+s?oN@393Jiz$?-;GrO8<# zmAG)hyu62|FIriUyCDCe1q^YcQ^X_~jZ`emv{2)jj(aU`rK}$qB&kaz;p8q6k4w75 zFhWPaL)fVLCgK&kq)q}!x(peUFtbyP95B}HGE|$K`0g<=a|%t24oN?euOm8}S>jS` zrF`7tGTZ5gk%>l=tHx$Frt=$X4OnqpjOv#$$$Pc;4SU)*g)h5dD zTpLl?-6rA#SpWu%Iw2mxH7CRf+;T#g@y8RQ0$=brxs!d=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "e2d76a7f5b07363c774e399c890552dd45d74d6379661d4c16710165b6a8a3ce" + "sha256": "0713e18ccbe77151eb7ed563e87385a503e913f2310e6ae7a1072efd34d7af92" } } } diff --git a/integrations/godot/plugin/src/service.ts b/integrations/godot/plugin/src/service.ts deleted file mode 100644 index 29aa3ef..0000000 --- a/integrations/godot/plugin/src/service.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { readFile } from "node:fs/promises" -import { Agent, request } from "node:http" -import { homedir } from "node:os" -import { join } from "node:path" -import { Readable } from "node:stream" - -const agent = new Agent({ keepAlive: true, proxyEnv: {} }) - -function serviceURL(value: string) { - if (!/^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/.test(value)) - throw new Error("OpenCode service requires a literal loopback HTTP URL") - const url = new URL(value) - if (url.username || url.password || url.hash) throw new Error("Invalid OpenCode service URL") - return url -} - -// A dedicated HTTP agent bypasses environment/system proxies; redirects are never followed. -export function serviceFetch(baseUrl: string): typeof globalThis.fetch { - const origin = serviceURL(baseUrl).origin - return async (input, init) => { - const message = new Request(input, init) - if (serviceURL(message.url).origin !== origin) throw new Error("OpenCode service origin changed") - const body = message.body ? Buffer.from(await message.arrayBuffer()) : undefined - message.signal.throwIfAborted() - return new Promise((resolve, reject) => { - const req = request( - message.url, - { - agent, - method: message.method, - headers: Object.fromEntries(message.headers), - signal: message.signal, - }, - (response) => { - const status = response.statusCode ?? 500 - if (status >= 300 && status < 400) { - response.resume() - reject(new Error("OpenCode service redirect refused")) - return - } - const headers = new Headers() - for (const [key, value] of Object.entries(response.headers)) { - for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) - headers.append(key, item) - } - resolve( - new Response( - message.method === "HEAD" || [204, 205, 304].includes(status) - ? null - : (Readable.toWeb(response) as ReadableStream), - { status, headers }, - ), - ) - }, - ) - req.on("error", reject) - req.once("abort", () => reject(message.signal.reason ?? new Error("OpenCode request aborted"))) - req.end(body) - }) - } -} - -export async function discoverService( - file = join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "opencode", "service.json"), -) { - try { - const registration = JSON.parse(await readFile(file, "utf8")) - if ( - typeof registration.url !== "string" || - !Number.isInteger(registration.pid) || - registration.pid <= 0 || - typeof registration.version !== "string" || - !registration.version - ) - return undefined - const fetch = serviceFetch(registration.url) - const headers: Record = {} - if (typeof registration.password === "string") - headers.authorization = `Basic ${Buffer.from(`opencode:${registration.password}`).toString("base64")}` - const response = await fetch(`${registration.url.replace(/\/$/, "")}/api/info`, { - headers, - signal: AbortSignal.timeout(3000), - }) - if (!response.ok) return undefined - const info = await response.json() - if (info?.pid !== registration.pid || info?.version !== registration.version) return undefined - return { url: registration.url as string, headers, fetch } - } catch { - return undefined - } -} diff --git a/integrations/godot/plugin/src/sidecar-core.ts b/integrations/godot/plugin/src/sidecar-core.ts index 57699a8..c6ab5cf 100644 --- a/integrations/godot/plugin/src/sidecar-core.ts +++ b/integrations/godot/plugin/src/sidecar-core.ts @@ -1,20 +1,21 @@ -import { createPanel as createChat, type PanelDependencies } from "../../../../packages/integration-kit/src/panel.ts" +import { + createPanel as createChat, + type PanelDependencies, + type PanelHost, +} from "../../../../packages/integration-kit/src/panel.ts" export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" export const PROJECT_MARKER = "opencode_godot_project" -export const createPanel = (deps: PanelDependencies) => - createChat( - { - app: "Godot", - rpcID: "neuralnomads.godot", - marker: PROJECT_MARKER, - document: "project", - keyField: "project_key", - nameField: "project_name", - defaultName: "project", - duplicateOffer: "Godot editors", - agent: true, - }, - deps, - ) +export const panelHost = { + app: "Godot", + rpcID: "neuralnomads.godot", + marker: PROJECT_MARKER, + document: "project", + keyField: "project_key", + nameField: "project_name", + defaultName: "project", + duplicateOffer: "Godot editors", + agent: true, +} satisfies PanelHost +export const createPanel = (deps: PanelDependencies) => createChat(panelHost, deps) diff --git a/integrations/godot/plugin/src/sidecar.ts b/integrations/godot/plugin/src/sidecar.ts index 5aba5ff..535b9cc 100644 --- a/integrations/godot/plugin/src/sidecar.ts +++ b/integrations/godot/plugin/src/sidecar.ts @@ -1,35 +1,4 @@ -// The OpenCode dock's private JSONL client, built into the add-on as sidecar.cjs and run by Node from the editor. -import readline from "node:readline" -import { OpenCode } from "@opencode/client" -import { discoverService } from "./service.ts" -import { createPanel, type PanelRequest } from "./sidecar-core.ts" +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" +import { panelHost } from "./sidecar-core.ts" -const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) -const panel = createPanel({ - send, - discover: async () => { - const endpoint = await discoverService() - return endpoint && OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers, fetch: endpoint.fetch }) - }, -}) -const queues = new Map>() - -const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) -input.on("line", (line) => { - if (!line.trim()) return - try { - if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") - const request = JSON.parse(line) as PanelRequest - if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") - const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => panel.dispatch(request)) - queues.set(request.channel, next) - void next.finally(() => { - if (queues.get(request.channel) === next) queues.delete(request.channel) - }) - } catch { - send({ error: { message: "Invalid panel request." } }) - } -}) -input.on("close", () => { - void panel.closeAll().finally(() => process.exit(0)) -}) +runPanel(panelHost) diff --git a/packages/integration-kit/src/panel-pipes.ts b/packages/integration-kit/src/panel-pipes.ts index c92d327..09c29c7 100644 --- a/packages/integration-kit/src/panel-pipes.ts +++ b/packages/integration-kit/src/panel-pipes.ts @@ -30,8 +30,8 @@ export function runPanel(config: PanelHost) { } }) input.on("close", () => { - void Promise.allSettled(queues.values()) - .then(panel.closeAll) - .finally(() => process.exit(0)) + // Blender can close its pipe while Connect is pending. Detach if that Connect reaches the service. + const closed = config.consoleEvents ? Promise.allSettled(queues.values()).then(panel.closeAll) : panel.closeAll() + void closed.finally(() => process.exit(0)) }) } From 6ee9a4e8393468d0ef89eeb0062d2b3f5dd0649d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:34:22 +0100 Subject: [PATCH 03/13] Connect in-app chat automatically and share conversations by folder --- .../host/opencode_link/_console_opencode.py | 322 +++++++++----- .../blender/host/opencode_link/addon.py | 13 +- .../blender/host/opencode_link/advertiser.py | 2 +- .../host/opencode_link/opencode_service.py | 26 +- integrations/blender/plugin/README.md | 2 +- .../host/blender/opencode_link-0.4.8.zip | Bin 986952 -> 998661 bytes integrations/blender/plugin/package.json | 2 +- .../blender/plugin/src/console-panel.ts | 4 - .../blender/test/console-chat.test.ts | 14 +- .../blender/test/console_chat_test.py | 8 +- integrations/blender/test/e2e.test.ts | 2 +- .../host/python/GafferOpenCode/Advertiser.py | 17 +- .../host/python/GafferOpenCode/__init__.py | 5 + .../host/python/GafferOpenCodeUI/Client.py | 72 ++- .../python/GafferOpenCodeUI/OpenCodeEditor.py | 134 +++--- integrations/gaffer/plugin/README.md | 4 +- .../host/gaffer/opencode_link-0.3.0.zip | Bin 253647 -> 261978 bytes integrations/gaffer/plugin/package.json | 2 +- .../gaffer/plugin/src/sidecar-core.ts | 5 - integrations/gaffer/test/panel.test.ts | 389 +---------------- integrations/gaffer/test/panel_probe.py | 68 +-- .../godot/host/addons/opencode_link/dock.gd | 204 +++++---- .../godot/host/addons/opencode_link/plugin.gd | 2 + .../host/addons/opencode_link/service.gd | 26 +- integrations/godot/plugin/README.md | 6 +- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 181643 -> 189665 bytes integrations/godot/plugin/package.json | 2 +- integrations/godot/plugin/src/sidecar-core.ts | 5 - integrations/godot/test/godot.test.ts | 8 +- integrations/godot/test/panel.test.ts | 386 ---------------- .../host/scripts/opencode_houdini/__init__.py | 4 + .../scripts/opencode_houdini/advertiser.py | 6 +- .../host/scripts/opencode_houdini/panel.py | 184 +++++--- integrations/houdini/plugin/README.md | 4 +- .../host/houdini/opencode_link-0.3.1.zip | Bin 265348 -> 252881 bytes integrations/houdini/plugin/package.json | 2 +- .../houdini/plugin/src/sidecar-steps.ts | 65 --- integrations/houdini/plugin/src/sidecar.ts | 261 +---------- integrations/houdini/test/host_probe.py | 1 + integrations/houdini/test/panel_probe.py | 19 +- .../houdini/test/sidecar-steps.test.ts | 89 ---- .../python/opencode_service.py | 26 +- packages/integration-kit/src/contract.ts | 17 +- .../integration-kit/src/integration-rpc.ts | 13 +- .../integration-kit/src/offer-registry.ts | 10 +- packages/integration-kit/src/panel-pipes.ts | 12 +- packages/integration-kit/src/panel.ts | 411 ++++++++++++------ .../integration-kit/src/session-bindings.ts | 4 +- packages/integration-kit/test/panel.test.ts | 154 +++++++ .../test/panel_launcher_test.py | 28 ++ 50 files changed, 1242 insertions(+), 1798 deletions(-) delete mode 100644 integrations/godot/test/panel.test.ts delete mode 100644 integrations/houdini/plugin/src/sidecar-steps.ts delete mode 100644 integrations/houdini/test/sidecar-steps.test.ts create mode 100644 packages/integration-kit/test/panel.test.ts create mode 100644 packages/integration-kit/test/panel_launcher_test.py diff --git a/integrations/blender/host/opencode_link/_console_opencode.py b/integrations/blender/host/opencode_link/_console_opencode.py index e282063..576f6bb 100644 --- a/integrations/blender/host/opencode_link/_console_opencode.py +++ b/integrations/blender/host/opencode_link/_console_opencode.py @@ -6,17 +6,19 @@ from pathlib import Path import queue import re -import shutil import subprocess import sys +import tempfile import threading +import time import uuid import bpy -from .opencode_service import registration_name +from .opencode_service import panel_launcher, registration_name +from .process import state as process_state -HELP = "/connect /stop /disconnect /new /status /help /allow /reject" +HELP = "/list /open /new /stop /status /help /allow /reject" INTERVAL = 0.05 @@ -45,28 +47,29 @@ def feed(self, text, end=False): class Pipes: - def __init__(self): + def __init__(self, launcher): self.out = queue.Queue() self.inbox = queue.Queue() - threading.Thread(target=self._read, daemon=True).start() + threading.Thread(target=self._read, args=launcher, daemon=True).start() - def _read(self): + def _read(self, runtime, bun): def failed(message): self.out.put({"event": "exit", "data": {"message": message}}) - node = shutil.which(os.environ.get("NEURALNOMADS_BLENDER_NODE") or "node") - if not node: - return failed("Node.js 22+ not found. Set NEURALNOMADS_BLENDER_NODE or add Node to PATH.") script = Path(__file__).with_name("sidecar.cjs") if not script.is_file(): return failed("Console sidecar missing. Install the built OpenCode Link add-on.") + env = os.environ.copy() + env.pop("BUN_BE_BUN", None) + if bun: + env["BUN_BE_BUN"] = "1" try: proc = subprocess.Popen( - [node, str(script)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + [runtime, str(script)], env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), ) except OSError: - return failed("Could not start Node.js.") + return failed("Could not start the OpenCode sidecar runtime.") def write(): with proc.stdin: @@ -86,7 +89,7 @@ def write(): pass self.inbox.put(None) proc.wait() - failed("Console sidecar exited. Use /connect to try again.") + failed("") class Chat: @@ -94,15 +97,28 @@ def __init__(self): self.pipes = None self.lines = Lines() self.permission = {} - self.path = "" - self.request = None - self.state, self.agent, self.model = "Disconnected", "", "" + self.target = None + self.unsent = [] + self.entries = [] + self.numbered = [] + self.menu_time = 0 + self.redraw = False + self.show_list = False + self.selected = None + self.draft = False + self.active = False + self.problem = "" + self.retry_at = 0 + self.state, self.agent, self.model = "Connecting", "", "" def send(self, method, **params): - if self.pipes is None: - self.pipes = Pipes() request = uuid.uuid4().hex - self.pipes.inbox.put({"id": request, "channel": "blender", "method": method, "params": params}) + if self.pipes: + self.pipes.inbox.put({"id": request, "channel": "blender", "method": method, "params": params}) + elif method == "prompt": + self.unsent.append(params) + elif method == "interrupt": + self.unsent.clear() return request def close(self): @@ -113,8 +129,33 @@ def close(self): def status(self): name = os.path.basename(bpy.data.filepath) or "Untitled" + if self.problem: + return f"OpenCode | {name} | {self.problem}" return f"OpenCode | {name} | {self.state} | agent: {self.agent or 'default'} | model: {self.model or 'default'}" + def blocked(self, message, append): + if message != self.problem: + self.problem = message + if message: + append("INFO", self.status()) + + def sync(self, target): + if target != self.target: + if target and self.target and target["directory"] != self.target["directory"]: + self.unsent.clear() + self.entries = [] + self.numbered = [] + self.selected = None + self.draft = False + self.target = target + self.state, self.agent, self.model = "Connecting", "", "" + self.lines = Lines() + self.permission.clear() + if target is not None: + self.send("connect", **target) + elif self.pipes: + self.send("close") + def drain(self, append, limit=120): if not self.pipes: return @@ -135,35 +176,37 @@ def output(text="", end=False): append("OUTPUT", line) if name == "exit": - append("ERROR", data["message"]) - self.close() - elif name == "error": - append("ERROR", data["message"]) - elif item.get("id") and self.request and item["id"] == self.request[0]: - method = self.request[1] - self.request = None - if method == "close": - self.close() - append("INFO", "Disconnected.") - elif method in ("connect", "new_session") and item.get("error"): - self.state = "Disconnected" - elif method == "prompt" and item.get("error"): - self.state = "Ready" - elif method == "interrupt" and not item.get("error"): - append("INFO", "Stop requested.") - elif self.state == "Disconnecting": - return - elif name == "disconnected": - self.state = "Disconnected" - self.permission.clear() output(end=True) - append("ERROR", data["message"]) - elif self.state == "Disconnected": - return + self.pipes = None + self.state = "Connecting" + self.retry_at = time.monotonic() + 2 + self.blocked(data["message"], append) + elif name == "error": + if self.state == "Connecting": + self.blocked(data["message"], append) + else: + append("ERROR", data["message"]) + elif name == "notice": + append("INFO", data["message"]) elif name == "session": + self.selected = data["id"] + self.draft = data.get("draft", False) self.state, self.agent, self.model = "Ready", data.get("agent"), data.get("model") - append("INFO", "Resumed conversation." if data.get("resumed") else "New conversation attached.") + self.problem = "" + if self.selected: + append("INFO", "Resumed conversation." if data.get("resumed") else "New conversation attached.") append("INFO", self.status()) + elif name == "conversations": + self.entries = data["entries"] + self.redraw = True + if self.show_list: + self.show_list = False + self.numbered = self.entries + for i, entry in enumerate(self.numbered, 1): + mark = "*" if entry["id"] == data.get("selected") else " " + append("INFO", f"{mark}{i}. {entry['title']}") + if not self.numbered: + append("INFO", "No conversations in this folder yet.") elif name == "assistant_delta": output(data["text"]) elif name == "assistant_end": @@ -173,7 +216,10 @@ def output(text="", end=False): duration = "" if elapsed is None else f" ({elapsed / 1000:.2f} s)" append("INFO", f"Tool: {data.get('name') or 'tool'} — {data['state']}{duration}") elif name == "status": - self.state = "Working" if data["state"] == "busy" else "Ready" + self.state = {"busy": "Working", "connecting": "Connecting"}.get(data["state"], "Ready") + if self.state == "Connecting": + output(end=True) + self.permission.clear() if self.state == "Ready": output(end=True) self.permission.clear() @@ -200,64 +246,74 @@ def _append(kind, text): bpy.ops.console.scrollback_append(text=text, type=kind) -def _broadcast(rows): - for window in bpy.context.window_manager.windows: +def _areas(): + manager = getattr(bpy.context, "window_manager", None) + for window in manager.windows if manager else (): for area in window.screen.areas: if area.type != "CONSOLE" or area.spaces.active.language != "opencode": continue region = next((r for r in area.regions if r.type == "WINDOW"), None) if region is not None: - with bpy.context.temp_override(window=window, area=area, region=region): - for kind, text in rows: - _append(kind, text) - area.tag_redraw() + yield window, area, region def _drain(): + areas = list(_areas()) + chat.active = chat.active or bool(areas) + if not chat.active: + return 0.5 rows = [] - chat.drain(lambda kind, text: rows.append((kind, text))) - if rows: - _broadcast(rows) - return INTERVAL if chat.pipes else None - - -def disconnect(): - if chat.pipes and chat.state != "Disconnecting": - chat.state = "Disconnecting" - chat.request = (chat.send("close"), "close") - - -def check_document(): - if chat.path and chat.path != bpy.data.filepath: - disconnect() - - -def _connect(method): + def append(kind, text): + rows.append((kind, text)) + _sync(append) + chat.drain(append) + if rows or chat.redraw: + for window, area, region in areas: + with bpy.context.temp_override(window=window, area=area, region=region): + for kind, text in rows: + _append(kind, text) + area.tag_redraw() + chat.redraw = False + return INTERVAL + + +def _sync(append): from .addon import preferences, session + if time.monotonic() < chat.retry_at: + return path = bpy.data.filepath - if not path: - return _append("ERROR", "Save this .blend before connecting.") + if path: + directory = os.path.dirname(path) + else: + process = process_state() + if not getattr(process, "console_unsaved_folder", None): + process.console_unsaved_folder = tempfile.TemporaryDirectory(prefix="opencode-blender-") + directory = process.console_unsaved_folder.name host = session() port, token, handle, label = host.snapshot() if host else (0, None, "", "") - if not token: - return _append("ERROR", "OpenCode Link is not offering this Blender yet.") try: - registration = registration_name(preferences().service_name.strip()) + prefs = preferences() + registration = registration_name(prefs.service_name.strip()) if prefs else None except (ValueError, AttributeError): - return _append("ERROR", "Invalid OpenCode service name in OpenCode Link preferences.") - chat.path = path - chat.state, chat.agent, chat.model = "Connecting", "", "" - chat.permission.clear() - chat.lines = Lines() - chat.request = (chat.send( - method, host="127.0.0.1", port=port, token=token, script_handle=handle, offer_label=label, - directory=os.path.dirname(path), document_name=os.path.basename(path), - document_key=os.path.normcase(os.path.abspath(path)), registration=registration, - ), method) - if not bpy.app.timers.is_registered(_drain): - bpy.app.timers.register(_drain, first_interval=0, persistent=True) - _append("INFO", "Connecting to OpenCode…") + chat.sync(None) + return chat.blocked("Invalid OpenCode service name in OpenCode Link preferences.", append) + chat.sync(dict( + host="127.0.0.1", port=port, token=token, script_handle=handle, offer_label=label, + directory=directory, + registration=registration, + )) + if not chat.pipes: + services = host.advertiser.results if host and host.advertiser else [] + launcher = panel_launcher(services, "NEURALNOMADS_BLENDER_NODE") + if launcher[0]: + chat.pipes = Pipes(launcher) + chat.send("connect", **chat.target, session_id=chat.selected, draft=chat.draft) + for params in chat.unsent: + chat.send("prompt", **params) + chat.unsent.clear() + elif services: + chat.blocked("No OpenCode runtime, NEURALNOMADS_BLENDER_NODE executable, or Node on PATH.", append) def execute(context, is_interactive): @@ -267,25 +323,31 @@ def execute(context, is_interactive): return {"CANCELLED"} _append("INPUT", "> " + text) bpy.ops.console.history_append(text="", current_character=0, remove_duplicates=True) - check_document() + chat.active = True + _sync(_append) if text in ("/help", "/status"): _append("INFO", HELP if text == "/help" else chat.status()) - elif text in ("/connect", "/new"): - if chat.state in ("Connecting", "Working", "Disconnecting"): - _append("INFO", "Wait for the current operation or use /stop.") - else: - _connect("connect" if text == "/connect" else "new_session") - elif text == "/disconnect": + elif text == "/list": if chat.pipes: - disconnect() + chat.show_list = True + chat.send("list") + else: + _append("INFO", chat.status()) + elif text.startswith("/open "): + index = text[6:].strip() + if chat.pipes and index.isascii() and index.isdecimal() and len(index) < 8 and 1 <= int(index) <= len(chat.numbered): + chat.send("open", session_id=chat.numbered[int(index) - 1]["id"]) else: - _append("INFO", "Disconnected.") + _append("INFO", "Use /list, then /open .") + elif text == "/new": + if chat.state == "Ready" and chat.target: + chat.send("new_session", **chat.target) + else: + _append("INFO", "Wait for OpenCode to be ready.") elif text.startswith("/") and text not in ("/stop", "/allow", "/reject"): _append("ERROR", "Unknown command. Use /help.") - elif chat.state not in ("Ready", "Working"): - _append("INFO", "Use /connect first.") elif text == "/stop": - chat.request = (chat.send("interrupt"), "interrupt") + chat.send("interrupt") elif text in ("/allow", "/reject"): if len(chat.permission) == 1: request_id = next(iter(chat.permission)) @@ -296,9 +358,10 @@ def execute(context, is_interactive): _append("INFO", "No permission is pending.") elif chat.state == "Working": _append("INFO", "OpenCode is working. Wait or use /stop.") + elif chat.target: + chat.send("prompt", text=text) else: - chat.state = "Working" - chat.request = (chat.send("prompt", text=text), "prompt") + _append("INFO", chat.status()) return {"FINISHED"} @@ -313,23 +376,78 @@ def copy_as_script(context): def banner(context): + chat.active = True + _sync(_append) context.space_data.prompt = "> " _append("INFO", chat.status()) _append("INFO", HELP) return {"FINISHED"} +def _header(self, context): + if context.space_data.language == "opencode": + selected = next((entry["title"] for entry in chat.entries if entry["id"] == chat.selected), "New conversation") + self.layout.menu("OPENCODE_MT_conversations", text=selected) + + +def _menu_classes(): + # Blender is optional for the pipe/console unit tests. + class OPENCODE_OT_console_conversation(bpy.types.Operator): + bl_idname = "opencode.console_conversation" + bl_label = "Open conversation" + session_id: bpy.props.StringProperty() + + def execute(self, _context): + if self.session_id and chat.pipes: + chat.send("open", session_id=self.session_id) + elif chat.state == "Ready" and chat.target: + chat.send("new_session", **chat.target) + return {"FINISHED"} + + class OPENCODE_MT_conversations(bpy.types.Menu): + bl_label = "Conversations" + + def draw(self, _context): + now = time.monotonic() + if chat.pipes and now - chat.menu_time >= 1: + chat.menu_time = now + chat.send("list") + for entry in chat.entries: + item = self.layout.operator( + "opencode.console_conversation", text=entry["title"], + icon="CHECKMARK" if entry["id"] == chat.selected else "NONE", + ) + item.session_id = entry["id"] + self.layout.operator("opencode.console_conversation", text="New conversation", icon="ADD").session_id = "" + + return OPENCODE_OT_console_conversation, OPENCODE_MT_conversations + + +_classes = () + + def register(): + global _classes # Blender 5.3 lists loaded _console_* modules (and imports them by this name on Enter). sys.modules["_console_opencode"] = sys.modules[__name__] + _classes = _menu_classes() + for cls in _classes: + bpy.utils.register_class(cls) + bpy.types.CONSOLE_HT_header.append(_header) + bpy.app.timers.register(_drain, first_interval=0, persistent=True) -def unregister(): +def unregister(keep_language=False): + global _classes chat.close() if bpy.app.timers.is_registered(_drain): bpy.app.timers.unregister(_drain) if "_console_opencode" in sys.modules: - for screen in bpy.data.screens: + bpy.types.CONSOLE_HT_header.remove(_header) + for cls in reversed(_classes): + bpy.utils.unregister_class(cls) + _classes = () + for screen in (() if keep_language else bpy.data.screens): for area in screen.areas: for space in area.spaces: if space.type == "CONSOLE" and space.language == "opencode": diff --git a/integrations/blender/host/opencode_link/addon.py b/integrations/blender/host/opencode_link/addon.py index 0ff3c82..caca67f 100644 --- a/integrations/blender/host/opencode_link/addon.py +++ b/integrations/blender/host/opencode_link/addon.py @@ -120,6 +120,7 @@ def pump(seconds, stop=None): _reload_at = None _quit_at = None _quit_requested = False +_reloading = False def schedule_quit(): @@ -160,7 +161,7 @@ def schedule_reload(): def run_pending_reload(): """Disable the add-on, drop its modules and enable it again from disk, which offers the session again: a new listener, token and script handle (references are invalidated), the same offer key.""" - global _reload_at + global _reload_at, _reloading if _reload_at is None: return None _reload_at = None @@ -172,7 +173,11 @@ def run_pending_reload(): return RELOAD_DELAY if _session is not None: process_state().revision = _session.app.revision() - addon_utils.disable(__package__, default_set=False, handle_error=None) + _reloading = True + try: + addon_utils.disable(__package__, default_set=False, handle_error=None) + finally: + _reloading = False for name in [name for name in sys.modules if name == __package__ or name.startswith(__package__ + ".")]: del sys.modules[name] addon_utils.enable(__package__, default_set=False, handle_error=None) @@ -256,7 +261,6 @@ def _on_change(*_args): def _on_save(*args): if _session is not None: _session.app.saved(args[0] if args and isinstance(args[0], str) else None) - chat.check_document() @persistent @@ -267,7 +271,6 @@ def _on_history(*_args): @persistent def _on_load(*_args): - chat.disconnect() if _session is not None: _session.app.loaded() _session.core.quarantined = False @@ -335,7 +338,7 @@ def _start_offer(): def unregister(): global _session - chat.unregister() + chat.unregister(keep_language=_reloading) console.capture().uninstall() _remove_handlers() if _session is not None: diff --git a/integrations/blender/host/opencode_link/advertiser.py b/integrations/blender/host/opencode_link/advertiser.py index 4d67a56..7fdad16 100644 --- a/integrations/blender/host/opencode_link/advertiser.py +++ b/integrations/blender/host/opencode_link/advertiser.py @@ -43,7 +43,7 @@ def offer_label(document): name = (document or "Untitled").replace("/", " ").replace("\\", " ") name = "".join(char for char in name if ord(char) >= 32 and char != "\x7f").strip() or "Untitled" # Public selector for the in-app console: two Blender processes can open the same file. - suffix = " [%s]" % os.getpid() if document else "" + suffix = " [%s]" % os.getpid() return ("Blender: %s" % name)[:LABEL_MAX - len(suffix)] + suffix diff --git a/integrations/blender/host/opencode_link/opencode_service.py b/integrations/blender/host/opencode_link/opencode_service.py index 5354867..25451a0 100644 --- a/integrations/blender/host/opencode_link/opencode_service.py +++ b/integrations/blender/host/opencode_link/opencode_service.py @@ -29,6 +29,7 @@ import http.client import json import os +import shutil import re import time import urllib.error @@ -194,6 +195,14 @@ def _outcome(method, status, body): return value if status == 200 and value in OUTCOMES[method] else "error" +def panel_runtime(outcome, body): + if outcome in ("accepted", "renewed") and isinstance(body, dict): + runtime = body.get("output", {}).get("panel_runtime") + if isinstance(runtime, str) and os.path.isabs(runtime): + return {"panel_runtime": runtime} + return {} + + def _ready(service, rpc_id, directory, deadline): # Registration is asynchronous on cold Locations. Only the payload-free # status read is repeated; an advertisement/withdrawal is never a probe. @@ -213,6 +222,7 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env results = [] for service in discover(service_name, env, timeout): outcome = "unavailable" + runtime = {} for directory in location_candidates(config_dir_setting, env): try: deadline = time.monotonic() + timeout @@ -233,11 +243,25 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env outcome = "unavailable" else: outcome = _outcome(method, status, body) + if method == "advertise": + runtime = panel_runtime(outcome, body) break - results.append({"service": service.file, "outcome": outcome}) + results.append({"service": service.file, "outcome": outcome, **runtime}) return results +def panel_launcher(results, override): + """Use the daemon's advertised executable, then the host override, then Node on PATH.""" + for result in results: + runtime = result.get("panel_runtime") + if result.get("outcome") in ("accepted", "renewed") and isinstance(runtime, str) and os.path.isabs(runtime) and shutil.which(runtime): + return runtime, True + for candidate in (os.environ.get(override), "node"): + if candidate and (node := shutil.which(candidate)): + return node, False + return None, False + + def advertise_all(rpc_id, offer, service_name=None, config_dir_setting=None, env=None, timeout=TIMEOUT): """Advertise one offer to every discovered service, or to the named one.""" return _each_service("advertise", rpc_id, offer, service_name, config_dir_setting, env, timeout) diff --git a/integrations/blender/plugin/README.md b/integrations/blender/plugin/README.md index 1b62858..e3fe61d 100644 --- a/integrations/blender/plugin/README.md +++ b/integrations/blender/plugin/README.md @@ -34,7 +34,7 @@ The **Plugins** section lists OpenCode for Blender as an integration: its versio ## Chat in Blender (prototype) -With OpenCode running and OpenCode Link enabled, save your `.blend`, open a **Python Console** editor (`Shift–F4`), then choose **Console → Languages → Opencode**. Enter `/connect` to resume that file's conversation or start one, then type a message and press Enter. `/new` starts a fresh conversation, `/stop` interrupts the current turn, and `/disconnect` detaches only this conversation. Use `/status` or `/help` at any time. Node.js 22+ must be on `PATH`, or set `NEURALNOMADS_BLENDER_NODE` to its executable. The console uses the shared OpenCode service unless another service is named in the add-on preferences. +With OpenCode running and OpenCode Link enabled, open a **Python Console** (`Shift–F4`) and choose **Console → Languages → Opencode**. It connects on its own, even for an unsaved scene, and keeps the current conversation when you open another file in the same folder. Use the conversation menu in the header, or `/list` then `/open `, to switch. **New conversation** (`/new`) stays empty until you send a message. `/stop` interrupts or clears queued messages; `/status` and `/help` are always available. The console uses OpenCode’s executable; Node.js 22+ (`NEURALNOMADS_BLENDER_NODE` or `PATH`) is only a fallback. The add-on preferences can target a named OpenCode service. The Console wraps lines and keeps its own Up-arrow history. An unfinished line appears when the stream finishes or the next newline arrives. **Copy as Script** copies this area's scrollback as plain text, not executable Python. Earlier messages stay in OpenCode when you reconnect; they are not replayed into Blender. `/allow` approves a single pending OpenCode permission once; `/reject` declines it. Use OpenCode to handle questions or multiple pending approvals. diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 0040c8b7311059830fd229456761bfe6cd8c6243..c6a510fd7c5d8e8db91d559ce6b1fcc243718959 100644 GIT binary patch delta 16417 zcmb7L3w%`7na|ARF*7;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EsMkD@o5V%=fF;qO1SqML`MwK0h z^pPLl?aYBc-|ZwYX(kT8d{iHPYS5VvFFl#54ZGpMOcY{&RG+&r6L;I6U|-hTM*az; zS=?%8^B*!TcpfZ=v-jgw@Y8eA{x4^7 zmB!7*{g1BI#;f(Ab3INsV$A$G5q2^=;JPi&DQv+s`yaPD!M)e%)0aE$9JSZK?SlF9 zxEfo{QMi5{H#d9bDSSN=7K6P(XbYg0ug*iy9lih`&Esa-Z}`LsQ)@7G&uxHk4Oh$k zD#vA!@JQM%wqx&PMC{9QSGv9Ll)&4#*0!HQaVlW6V(3-4P|KA}OkG=8E!m^qzwbX?kX6Ucwk^F68tb^3&S(FQSn!@# v(vh^U4yE+8!b5f3+|se{J5+4U diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index 455ef68..df17e34 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.4.8", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "491b63857e2856d9fa680c6a6db562c60dbc6d4bf4d74e708465cc9c2be704d1" + "sha256": "ed8ec9be1fdb6464765a343782fe42823a6c6b3fce1e34cbc86942b88c5ba246" } } } diff --git a/integrations/blender/plugin/src/console-panel.ts b/integrations/blender/plugin/src/console-panel.ts index c70b468..5df56ff 100644 --- a/integrations/blender/plugin/src/console-panel.ts +++ b/integrations/blender/plugin/src/console-panel.ts @@ -3,11 +3,7 @@ import type { PanelHost } from "../../../../packages/integration-kit/src/panel.t export const blenderPanel = { app: "Blender", rpcID: "neuralnomads.blender", - marker: "opencode_blender_document", document: "document", - keyField: "document_key", - nameField: "document_name", - defaultName: "Untitled", duplicateOffer: "Blender instances", agent: true, consoleEvents: true, diff --git a/integrations/blender/test/console-chat.test.ts b/integrations/blender/test/console-chat.test.ts index ae6ac63..0921644 100644 --- a/integrations/blender/test/console-chat.test.ts +++ b/integrations/blender/test/console-chat.test.ts @@ -14,12 +14,12 @@ it("formats and fans out streamed lines in the Blender timer without bpy", () => assert.equal(result.status, 0, result.error?.message ?? result.stderr) }) -it("the shared sidecar binds only Blender's marked conversation and streams tools and interruption", async () => { +it("the sidecar resumes a folder conversation and streams wrapped tool names and interruption", async () => { const calls: unknown[] = [] const out: unknown[] = [] const bindings = new Map([["ses_codenomad", "offer_here"]]) const location = { directory: import.meta.dirname } - const session = { id: "ses_console", agent: "build", metadata: { [blenderPanel.marker]: "test.blend" } } + const session = { id: "ses_console", agent: "build", time: { updated: 2 } } let push: (value: unknown) => void = () => {} const api = { rpc: (rpc: { id: string }) => { @@ -101,17 +101,23 @@ it("the shared sidecar binds only Blender's marked conversation and streams tool await emit("session.text.delta", { delta: "hello\n" }) await emit("session.tool.input.started", { id: "tool_1", name: "blender_context" }) await emit("session.tool.success", { id: "tool_1" }) + await emit("session.tool.input.started", { id: "tool_2", name: "execute" }) + await emit("session.tool.called", { id: "tool_2", input: { code: "await tools.blender.context({})" } }) + await emit("session.tool.success", { id: "tool_2" }) await call("interrupt") await emit("session.execution.interrupted", {}) - assert.deepEqual(out.slice(0, 3), [ + assert.deepEqual(out.slice(0, 4), [ + event("user_message", { text: "hello" }), { id: "prompt", result: {} }, event("assistant_delta", { text: "hello\n" }), event("tool", { id: "tool_1", name: "blender_context", state: "starting" }), ]) - const completed = out[3] as { data: { name: string; state: string; duration_ms: number } } + const completed = out[4] as { data: { name: string; state: string; duration_ms: number } } assert.equal(completed.data.name, "blender_context") assert.equal(completed.data.state, "completed") assert.ok(completed.data.duration_ms >= 0) + assert.equal((out[5] as typeof completed).data.name, "blender_context") + assert.equal((out[6] as typeof completed).data.name, "blender_context") assert.deepEqual(out.at(-1), event("status", { state: "idle", interrupted: true })) assert.deepEqual(calls, [ { sessionID: session.id, text: "hello" }, diff --git a/integrations/blender/test/console_chat_test.py b/integrations/blender/test/console_chat_test.py index 8ffcb8d..32d9df0 100644 --- a/integrations/blender/test/console_chat_test.py +++ b/integrations/blender/test/console_chat_test.py @@ -42,6 +42,7 @@ def area(language): chat = console.chat = console.Chat() chat.pipes = NS(out=Queue(), inbox=Queue()) chat.state = "Working" + console._sync = lambda append: None def add(event, **data): chat.pipes.out.put({"event": event, "data": data}) @@ -60,9 +61,10 @@ def add(event, **data): self.assertEqual(second.rows, first.rows) self.assertEqual(first.redraws, 2) self.assertEqual(python.rows, []) - add("exit", message="sidecar closed") - self.assertIsNone(console._drain()) - self.assertEqual(first.rows[-1], {"text": "sidecar closed", "type": "ERROR"}) + add("exit", message="") + self.assertEqual(console._drain(), console.INTERVAL) + self.assertIsNone(chat.pipes) + self.assertEqual(chat.state, "Connecting") if __name__ == "__main__": diff --git a/integrations/blender/test/e2e.test.ts b/integrations/blender/test/e2e.test.ts index 2b4eb2e..90c2ebd 100644 --- a/integrations/blender/test/e2e.test.ts +++ b/integrations/blender/test/e2e.test.ts @@ -49,7 +49,7 @@ describe("OpenCode 2.2.5 service with a background Blender", { skip }, () => { return listed.offers.length > 0 ? listed.offers : undefined }) assert.equal(offers.length, 1) - assert.equal(offers[0]?.label, "Blender: Untitled") + assert.match(offers[0]?.label ?? "", /^Blender: Untitled \[\d+\]$/) assert.equal(offers[0]?.protocol, "ok") assert.deepEqual(await rpc("attachHost", { offerID: offers[0]?.offerID, sessionID: session.id }), { outcome: "attached", diff --git a/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py b/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py index ce50907..6ab4e1b 100644 --- a/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py +++ b/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py @@ -104,12 +104,13 @@ def __renew( self, offers ) : results, failed = [], False for name, ( service, directory ) in targets.items() : for offer in offers : + body = None try : status, body = opencode_service.call( service, RPC_ID, "advertise", offer, directory, RENEW_TIMEOUT ) outcome = opencode_service._outcome( "advertise", status, body ) except ( OSError, ValueError ) : outcome = "error" - results.append( { "service" : name, "label" : offer["label"], "outcome" : outcome } ) + results.append( { "service" : name, "label" : offer["label"], "outcome" : outcome, **opencode_service.panel_runtime( outcome, body ) } ) failed = failed or outcome not in ( "accepted", "renewed" ) if not failed : return results @@ -128,21 +129,21 @@ def __renew( self, offers ) : if opencode_service._unavailable( status, body ) : continue if status != 200 : - outcomes = [ ( offer, "error" ) for offer in offers ] + outcomes = [ ( offer, "error", None ) for offer in offers ] else : for offer in offers : try : status, body = opencode_service.call( service, RPC_ID, "advertise", offer, directory, max( 0.5, deadline - time.monotonic() ) ) - outcomes.append( ( offer, opencode_service._outcome( "advertise", status, body ) ) ) + outcomes.append( ( offer, opencode_service._outcome( "advertise", status, body ), body ) ) except ( OSError, ValueError ) : - outcomes.append( ( offer, "error" ) ) + outcomes.append( ( offer, "error", None ) ) except ( OSError, ValueError ) : - outcomes = [ ( offer, "error" ) for offer in offers ] - for offer, outcome in outcomes : - results.append( { "service" : service.file, "label" : offer["label"], "outcome" : outcome } ) - if any( outcome in ( "accepted", "renewed" ) for _, outcome in outcomes ) : + outcomes = [ ( offer, "error", None ) for offer in offers ] + for offer, outcome, body in outcomes : + results.append( { "service" : service.file, "label" : offer["label"], "outcome" : outcome, **opencode_service.panel_runtime( outcome, body ) } ) + if any( outcome in ( "accepted", "renewed" ) for _, outcome, _ in outcomes ) : found[service.file] = ( service, directory ) break else : diff --git a/integrations/gaffer/host/python/GafferOpenCode/__init__.py b/integrations/gaffer/host/python/GafferOpenCode/__init__.py index 631d140..fa37df2 100644 --- a/integrations/gaffer/host/python/GafferOpenCode/__init__.py +++ b/integrations/gaffer/host/python/GafferOpenCode/__init__.py @@ -105,6 +105,11 @@ def offerInfo( script ) : return { "label" : label, "offer_key" : key, "advertising" : __advertiser is not None } +def panelServices() : + + return __advertiser.results if __advertiser is not None else [] + + def scriptHandle( script ) : if __host is None : diff --git a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py index 2e1cb38..fcad60c 100644 --- a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py +++ b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py @@ -1,12 +1,13 @@ import json -import os import pathlib -import shutil import uuid import weakref from Qt import QtCore +from GafferOpenCode import panelServices +from GafferOpenCode.opencode_service import panel_launcher + class ClientProcess : @@ -29,10 +30,14 @@ def __init__( self ) : self.__process.finished.connect( self.__finished ) self.__process.errorOccurred.connect( self.__processError ) self.__channels = {} + self.__targets = {} self.__pending = [] self.__stdout = b"" self.__nextRequest = 0 - self.__start() + self.__problem = "" + self.__timer = QtCore.QTimer( self.__process ) + self.__timer.timeout.connect( self.__start ) + self.__timer.start( 1000 ) ## One panel's events; the callback is held weakly. def register( self, callback ) : @@ -51,18 +56,28 @@ def close( self, channel ) : return self.send( channel, "close", {} ) self.__channels.pop( channel, None ) + self.__targets.pop( channel, None ) + self.__pending = [item for item in self.__pending if item[0] != channel] def send( self, channel, method, params ) : - message = self.__message( channel, method, params ) + if method in ( "connect", "new_session" ) : + previous = self.__targets.get( channel, {} ) + if method == "new_session" or previous.get( "directory" ) != params.get( "directory" ) : + self.__pending = [item for item in self.__pending if item[0] != channel] + else : + params = { **params, "session_id" : previous.get( "session_id" ), "draft" : previous.get( "draft", False ) } + self.__targets[channel] = params if self.__process.state() == QtCore.QProcess.Running : - self.__process.write( message ) - else : + self.__process.write( self.__message( channel, method, params ) ) + elif method not in ( "connect", "new_session", "close" ) : + if method == "interrupt" : + self.__pending = [item for item in self.__pending if item[0] != channel or item[1] != "prompt"] if len( self.__pending ) >= 100 : self.__emit( channel, "error", { "message" : "OpenCode sidecar request queue is full" } ) return - self.__pending.append( message ) - self.__start() + self.__pending.append( ( channel, method, params ) ) + self.__start() def __message( self, channel, method, params ) : @@ -76,20 +91,25 @@ def __message( self, channel, method, params ) : def __start( self ) : - if self.__process.state() != QtCore.QProcess.NotRunning : - return - node = os.environ.get( "NEURALNOMADS_GAFFER_NODE" ) or shutil.which( "node" ) - if not node : - self.__pending = [] - self.__emitAll( "error", { "message" : "Install Node.js 22 or set NEURALNOMADS_GAFFER_NODE" } ) + if not self.__targets or self.__process.state() != QtCore.QProcess.NotRunning : return + services = panelServices() + runtime, bun = panel_launcher( services, "NEURALNOMADS_GAFFER_NODE" ) # Built into the installed part, beside the Python packages. sidecar = pathlib.Path( __file__ ).resolve().parents[2] / "sidecar.cjs" - if not sidecar.is_file() : - self.__pending = [] - self.__emitAll( "error", { "message" : "OpenCode Link sidecar is missing; reinstall the application part." } ) + problem = ( "OpenCode Link sidecar is missing; reinstall the application part." if not sidecar.is_file() else + "No OpenCode runtime, NEURALNOMADS_GAFFER_NODE executable, or Node on PATH." if not runtime else "" ) + if problem and services and problem != self.__problem : + self.__emitAll( "error", { "message" : problem } ) + self.__problem = problem + if problem : return - self.__process.setProgram( node ) + environment = QtCore.QProcessEnvironment.systemEnvironment() + environment.remove( "BUN_BE_BUN" ) + if bun : + environment.insert( "BUN_BE_BUN", "1" ) + self.__process.setProcessEnvironment( environment ) + self.__process.setProgram( runtime ) self.__process.setArguments( [ str( sidecar ) ] ) self.__process.setWorkingDirectory( str( sidecar.parent.parent ) ) self.__process.start() @@ -98,17 +118,19 @@ def __started( self ) : pending = self.__pending self.__pending = [] - for message in pending : - self.__process.write( message ) + self.__problem = "" + for channel, params in self.__targets.items() : + self.__process.write( self.__message( channel, "connect", params ) ) + for channel, method, params in pending : + self.__process.write( self.__message( channel, method, params ) ) def __finished( self, exitCode, unusedExitStatus ) : - self.__pending = [] - self.__emitAll( "error", { "message" : "OpenCode sidecar stopped with exit code " + str( exitCode ) } ) + self.__stdout = b"" + self.__emitAll( "status", { "state" : "connecting" } ) def __processError( self, unusedError ) : - self.__pending = [] self.__emitAll( "error", { "message" : "OpenCode sidecar process error: " + self.__process.errorString() } ) def __readStdout( self ) : @@ -126,8 +148,10 @@ def __readStdout( self ) : continue channel = message.get( "channel" ) if channel and message.get( "event" ) : + if message["event"] == "session" and channel in self.__targets : + self.__targets[channel] = { **self.__targets[channel], "session_id" : message["data"]["id"], "draft" : message["data"].get( "draft", False ) } self.__emit( channel, message["event"], message.get( "data" ) or {} ) - elif message.get( "error" ) : + elif message.get( "error" ) and not message.get( "id" ) : self.__emitAll( "error", message["error"] ) def __readStderr( self ) : diff --git a/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py b/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py index 339c6ec..567ccc2 100644 --- a/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py +++ b/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py @@ -1,5 +1,4 @@ import functools -import hashlib import os import pathlib import weakref @@ -32,8 +31,9 @@ def __init__( self, scriptNode, **kw ) : self.__header = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 6 ) self.__brand = GafferUI.Label( "OpenCode for Gaffer" ) self.__brand._qtWidget().setObjectName( "gafferOpenCodeBrand" ) - self.__sessionLabel = GafferUI.Label( "SESSION disconnected" ) - self.__sessionLabel._qtWidget().setObjectName( "gafferOpenCodeSession" ) + self.__conversations = [] + self.__selected = None + self.__conversationButton = GafferUI.MenuButton( "New conversation", menu = GafferUI.Menu( Gaffer.WeakMethod( self.__conversationMenu ) ) ) self.__models = [] self.__model = "" self.__modelButton = GafferUI.MenuButton( @@ -41,18 +41,13 @@ def __init__( self, scriptNode, **kw ) : menu = GafferUI.Menu( Gaffer.WeakMethod( self.__modelMenuDefinition ), title = "Model" ), ) self.__modelButton.setEnabled( False ) - self.__newButton = GafferUI.Button( "New" ) - self.__newButton.setEnabled( False ) - self.__connectButton = GafferUI.Button( "Connect" ) self.__header.append( self.__brand ) - self.__header.append( self.__sessionLabel ) self.__header.append( GafferUI.Spacer( imath.V2i( 1 ), maximumSize = imath.V2i( 100000, 1 ) ), expand = True ) - self.__statusLabel = GafferUI.Label( "DISCONNECTED" ) + self.__statusLabel = GafferUI.Label( "CONNECTING" ) self.__statusLabel._qtWidget().setObjectName( "gafferOpenCodeStatus" ) self.__header.append( self.__statusLabel ) self.__header.append( self.__modelButton ) - self.__header.append( self.__newButton ) - self.__header.append( self.__connectButton ) + self.__header.append( self.__conversationButton ) self.__column.append( self.__header ) self.__transcript = GafferUI.MultiLineTextWidget( @@ -81,7 +76,7 @@ def __init__( self, scriptNode, **kw ) : wrapMode = GafferUI.MultiLineTextWidget.WrapMode.Word, ) self.__sendButton = GafferUI.Button( "Send" ) - self.__sendButton.setEnabled( False ) + self.__sendButton.setEnabled( True ) self.__stopButton = GafferUI.Button( "Stop" ) self.__stopButton.setEnabled( False ) self.__promptRow.append( self.__prompt, expand = True ) @@ -97,8 +92,6 @@ def __init__( self, scriptNode, **kw ) : "#gafferOpenCodeTranscript { border-top: 1px solid #34393e; border-bottom: 1px solid #34393e; }" ) - self.__newButton.clickedSignal().connect( Gaffer.WeakMethod( self.__newSession ) ) - self.__connectButton.clickedSignal().connect( Gaffer.WeakMethod( self.__toggleConnection ) ) self.__sendButton.clickedSignal().connect( Gaffer.WeakMethod( self.__send ) ) self.__stopButton.clickedSignal().connect( Gaffer.WeakMethod( self.__stop ) ) self.__allowButton.clickedSignal().connect( Gaffer.WeakMethod( self.__allow ) ) @@ -112,14 +105,18 @@ def __init__( self, scriptNode, **kw ) : # panel is open; the panel only attaches its own conversation to that offer. self.__client = None self.__channel = None - self.__active = False self.__connected = False if not GafferOpenCode.scriptHandle( scriptNode ) : raise RuntimeError( "OpenCodeEditor requires a ScriptNode registered with the Gaffer application" ) - self.__scriptKey = self.__currentScriptKey() self.__scriptConnections = [ scriptNode.plugSetSignal().connect( Gaffer.WeakMethod( self.__scriptPlugSet ), scoped = True ), ] + GafferOpenCode.acquirePanel( self.__ensureChannel() ) + self.__target = None + self.__sync() + self.__timer = QtCore.QTimer( self._qtWidget() ) + self.__timer.timeout.connect( Gaffer.WeakMethod( self.__sync ) ) + self.__timer.start( 500 ) def __repr__( self ) : @@ -142,50 +139,18 @@ def __ensureChannel( self ) : weakref.finalize( self, OpenCodeEditor.__release, self.__client, self.__channel ) return self.__channel - def __toggleConnection( self, unusedButton = None ) : - - if self.__active : - self.__disconnect() - else : - self.__connect( "connect" ) - - def __connect( self, method ) : - + def __sync( self ) : params = self.__connectParams() - if params is None : - return - channel = self.__ensureChannel() - GafferOpenCode.acquirePanel( channel ) - self.__active = True - self.__connected = False - self.__connectButton.setText( "Disconnect" ) - self.__newButton.setEnabled( True ) - self.__statusLabel.setText( "CONNECTING" ) - self.__sendButton.setEnabled( False ) - self.__client.send( channel, method, params ) - - def __disconnect( self ) : - - self.__active = False - self.__connected = False - if self.__channel is not None : - self.__client.send( self.__channel, "close", {} ) - GafferOpenCode.releasePanel( self.__channel ) - self.__connectButton.setText( "Connect" ) - self.__statusLabel.setText( "DISCONNECTED" ) - self.__sendButton.setEnabled( False ) - self.__stopButton.setEnabled( False ) - self.__newButton.setEnabled( False ) - self.__modelButton.setEnabled( False ) + if params != self.__target : + self.__target = params + self.__client.send( self.__channel, "connect", params ) def __event( self, name, data ) : - if not self.__active and name != "error" : - return # a reply to a connection this editor has since closed if name == "session" : self.__connected = True - self.__sessionLabel.setText( "SESSION " + str( data.get( "id", "" ) )[-8:] ) - self.__sessionLabel.setToolTip( "Workspace: " + str( data.get( "workspace", "" ) ) ) + self.__selected = data.get( "id" ) + self.__conversationButton.setToolTip( "Workspace: " + str( data.get( "workspace", "" ) ) ) self.__setModel( str( data.get( "model", "" ) ) ) self.__append( "system", "Resumed session" if data.get( "resumed" ) else "New session" ) elif name == "models" : @@ -198,6 +163,15 @@ def __event( self, name, data ) : self.__transcript.setText( "" ) for message in data.get( "messages", [] ) : self.__append( message.get( "role", "system" ), message.get( "text", "" ) ) + elif name == "conversations" : + self.__conversations = data["entries"] + self.__selected = data.get( "selected" ) + title = next( (item["title"] for item in self.__conversations if item["id"] == self.__selected), "New conversation" ) + self.__conversationButton.setText( title ) + elif name == "notice" : + self.__append( "system", data["message"] ) + elif name == "user_message" : + self.__append( "user", data["text"] ) elif name == "assistant_start" : self.__startAssistant() elif name == "assistant_delta" : @@ -215,9 +189,13 @@ def __event( self, name, data ) : elif name == "status" : state = str( data.get( "state", "unknown" ) ) self.__statusLabel.setText( state.upper() ) + if state == "connecting" : + self.__connected = False + self.__permissionRequest = None + self.__permissionRow.setVisible( False ) self.__busy = state in ( "busy", "retry" ) - self.__stopButton.setEnabled( self.__busy ) - self.__sendButton.setEnabled( self.__connected and not self.__busy ) + self.__stopButton.setEnabled( self.__busy or state == "connecting" ) + self.__sendButton.setEnabled( not self.__busy ) self.__prompt.setEnabled( not self.__busy ) self.__modelButton.setEnabled( self.__connected and bool( self.__models ) and not self.__busy ) elif name == "error" : @@ -226,7 +204,7 @@ def __event( self, name, data ) : self.__busy = False self.__streaming = False self.__stopButton.setEnabled( False ) - self.__sendButton.setEnabled( self.__connected ) + self.__sendButton.setEnabled( True ) self.__prompt.setEnabled( True ) self.__modelButton.setEnabled( self.__connected and bool( self.__models ) ) @@ -261,30 +239,33 @@ def __selectModel( self, unusedMenu = None, model = "" ) : return self.__client.send( self.__channel, "switch_model", { "model" : model } ) - ## The conversation marked for this script is taken back at Connect: a saved script by its file, an unsaved - # one while it stays open. - def __currentScriptKey( self ) : + def __conversationMenu( self ) : - scriptNode = self.scriptNode() - fileName = str( scriptNode["fileName"].getValue() ) - if not fileName : - return "untitled:" + GafferOpenCode.scriptHandle( scriptNode ) - return "document:" + hashlib.sha256( str( pathlib.Path( fileName ).resolve() ).encode( "utf-8" ) ).hexdigest() + self.__client.send( self.__channel, "list", {} ) + menu = IECore.MenuDefinition() + menu.append( "/New conversation", { "command" : Gaffer.WeakMethod( self.__newSession ), "checkBox" : self.__selected is None, "active" : not self.__busy } ) + for i, item in enumerate( self.__conversations, 1 ) : + title = (item.get( "title" ) or "Untitled").replace( "/", "/" ) + menu.append( f"/{i}. {title}", { + "command" : functools.partial( Gaffer.WeakMethod( self.__openConversation ), item["id"] ), + "checkBox" : item["id"] == self.__selected, + "active" : not self.__busy, + } ) + return menu + + def __openConversation( self, session, unusedMenu = None ) : + + self.__client.send( self.__channel, "open", { "session_id" : session } ) def __connectParams( self ) : scriptNode = self.scriptNode() offer = GafferOpenCode.offerInfo( scriptNode ) - if not offer.get( "advertising" ) or not offer.get( "label" ) : - self.__append( "error", "OpenCode Link does not offer this script to OpenCode." ) - return None fileName = str( scriptNode["fileName"].getValue() ) params = dict( GafferOpenCode.hostInfo() ) params.update( { "script_handle" : GafferOpenCode.scriptHandle( scriptNode ), - "offer_label" : offer["label"], - "script_key" : self.__scriptKey, - "script_name" : pathlib.Path( fileName ).name if fileName else scriptNode.getName(), + "offer_label" : offer.get( "label" ), "directory" : str( pathlib.Path( fileName ).resolve().parent ) if fileName else os.getcwd(), } ) return params @@ -293,25 +274,20 @@ def __scriptPlugSet( self, plug ) : if not plug.isSame( self.scriptNode()["fileName"] ) : return - previousKey = self.__scriptKey - self.__scriptKey = self.__currentScriptKey() - # Another file is another script's conversation: Connect takes that one. - if self.__scriptKey != previousKey and self.__active : - self.__disconnect() + self.__sync() - def __newSession( self, unusedButton ) : + def __newSession( self, unusedButton = None ) : - self.__connect( "new_session" ) + self.__client.send( self.__channel, "new_session", self.__target ) def __send( self, unusedWidget ) : - if self.__busy or not self.__connected : + if self.__busy : return text = self.__prompt.getText().strip() if not text : return self.__prompt.setText( "" ) - self.__append( "user", text ) self.__client.send( self.__channel, "prompt", { "text" : text } ) def __stop( self, unusedButton ) : diff --git a/integrations/gaffer/plugin/README.md b/integrations/gaffer/plugin/README.md index 72a645c..9fb37fe 100644 --- a/integrations/gaffer/plugin/README.md +++ b/integrations/gaffer/plugin/README.md @@ -1,6 +1,6 @@ # OpenCode for Gaffer (preview) -Read, change and check the scripts open in Gaffer from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode for Gaffer** panel inside Gaffer. Gaffer 1.6 or later and OpenCode 2.2 or later are required; the panel also needs Node.js 22 or later. +Read, change and check the scripts open in Gaffer from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode for Gaffer** panel inside Gaffer. Gaffer 1.6 or later and OpenCode 2.2 or later are required. ## Install @@ -41,7 +41,7 @@ A call that outlasts its wait says whether Gaffer still runs it (OpenCode Link a ## The OpenCode for Gaffer panel -The **OpenCode for Gaffer** editor is a conversation inside Gaffer. **Connect** attaches the panel's conversation to its script's own offer, resuming the conversation it had for this script; **New** starts another. Closing the panel releases its conversation only: the script stays offered and other conversations attached to it keep it. The panel and other conversations (CodeNomad's, for instance) can be attached to the same script together; both write to it, each change checked against its revision. The panel's conversation lives in the script's folder: the first Connect there waits while OpenCode opens that folder and loads its plugins. A failed Connect says which step failed and why. Node.js is found on `PATH`; `NEURALNOMADS_GAFFER_NODE` names another one. +The **OpenCode for Gaffer** editor connects automatically to the latest conversation in the script’s folder. Opening another version in that folder keeps the selected conversation. The selector next to the model lists the folder’s conversations; **New conversation** creates nothing until you send a message. **Stop** interrupts the turn or clears queued prompts. The panel uses OpenCode’s executable, with Node.js 22+ (`NEURALNOMADS_GAFFER_NODE` or `PATH`) as a fallback. ## Limits diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index 0026d67d5bb729c7bcb076002c4e9edd95f9351a..e4938df70c28307a1dd9826b7db9d2d4cea10a6b 100644 GIT binary patch delta 14004 zcmbVT3v^WFozJ}=uSCMjgoHrg%NXDeOmD(d4Prneh;uT?g9|pxxbe?Zdj(+E$_Vl&(^>SoiF|27fOaerm(4!&An;U4KEp zliEjD(~VBfKK#cSTeM{fx@eJ;w{uA+W%qfuyE~n<&AgSfGktC$=clu_L7jr1bh37W z^40Of*ET$&Pe_PO-kI60!Dk#9UebJ1y?9LHG+tL*JKWj0VECV#=gG;#FEn?kx%#Z^ z|L5#sXV#S@LHj;)cvkuFEN#U-^{?eFdw)%RO%49GA*1CfPiUD7ws0P{2!=c(PP^*r zYF*nexH;O_XQg)AuAc^eP1p7c8Q-Jnfyi^3_Gr%WIg`}RcsA|nEql*s_i6Q~KR$Kl zU5T0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nOMUkaQ1;bK%#24qbTbYvk{m*I@~s{25f$8p`cy zYLk|c@;T};NnG6Z3#h>4>rhnc>!Z`I3n|6uYcQ{D`d)$DiBq)c;IAN@D;8rh*_c^J zYz#X0(V+0Ry0U$0)6lOPrWFm^Rd2&wsrmnydAR)F;A<6bP@QM2PNiZlWAVTlScNyn zsTFH@2ln8Daj3D+z5}rt73gGo5U6Q%0T(=Tsq0y!qLrDP zjD~ouvl1VA5gKsci%{C(oA6h;I`6FHp0R{N-H&paz05O5@wew;d$H@9`>KGP6UAO? z!~4%b!!>T5a}V$1O4m)djgR^xey8EoN7oMCeF6Hy8{2Q`x~Zpk{pwrRcHTm!gF0PB z#aqta0a@I1d)+Hnum#_^05?>)IUVCuw&DDbp?00GkJMMVdz^cx2zW+KCa1(uP|RhC z3eEa=b$j{8aCL5A@=ZUcKLeRPuweXpz5qY|3>ul=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "53db2a63cc4b1b7665bfc9b32362cc064b148f840d19980391bcf40feba589fc" + "sha256": "3f5dddc016acc88c87ff1f969833bf7b40cda7b8e26fe66b12a3c31ee93ceaee" } } } diff --git a/integrations/gaffer/plugin/src/sidecar-core.ts b/integrations/gaffer/plugin/src/sidecar-core.ts index 2f07d80..ca8d37a 100644 --- a/integrations/gaffer/plugin/src/sidecar-core.ts +++ b/integrations/gaffer/plugin/src/sidecar-core.ts @@ -6,15 +6,10 @@ import { export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" -export const SCRIPT_MARKER = "opencode_gaffer_script" export const panelHost = { app: "Gaffer", rpcID: "neuralnomads.gaffer", - marker: SCRIPT_MARKER, document: "script", - keyField: "script_key", - nameField: "script_name", - defaultName: "untitled", duplicateOffer: "scripts", } satisfies PanelHost export const createPanel = (deps: PanelDependencies) => createChat(panelHost, deps) diff --git a/integrations/gaffer/test/panel.test.ts b/integrations/gaffer/test/panel.test.ts index 71abbbc..8a0ddcd 100644 --- a/integrations/gaffer/test/panel.test.ts +++ b/integrations/gaffer/test/panel.test.ts @@ -1,49 +1,23 @@ import assert from "node:assert/strict" import { spawnSync } from "node:child_process" -import { cpSync, mkdtempSync, rmSync } from "node:fs" +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" -import { join } from "node:path" +import { dirname, join } from "node:path" import { it } from "node:test" -import { build } from "esbuild" -import { type Api, createPanel, SCRIPT_MARKER } from "../plugin/src/sidecar-core.ts" +import { readStoredZip } from "../../../packages/integration-kit/src/zip.ts" +import marker from "../plugin/package.json" with { type: "json" } -const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") -const KEY = "document:shot" -const HOST = { host: "127.0.0.1", port: 4242, token: "a".repeat(64) } -const CONNECT = { - ...HOST, - protocol: 1, - script_handle: "gaffer:shot", - offer_label: "Gaffer: shot.gfr", - script_key: KEY, - script_name: "shot.gfr", - directory: join(tmpdir(), "gaffer-shots"), -} - -it("the installed panel runs its sidecar with Node: payload layout, Gaffer stubs, no Bun", async () => { +it("the installed Gaffer panel opens automatically, queues early input and follows Save As", () => { const payload = mkdtempSync(join(tmpdir(), "gaffer-panel-")) try { - cpSync(join(import.meta.dirname, "..", "host", "python"), join(payload, "python"), { recursive: true }) - // As the host build makes it: one CommonJS file for Node 22 at the payload root. - await build({ - entryPoints: [join(import.meta.dirname, "..", "plugin", "src", "sidecar.ts")], - bundle: true, - format: "cjs", - platform: "node", - target: "node22", - outfile: join(payload, "sidecar.cjs"), - logLevel: "warning", - }) - const sidecar = spawnSync(process.execPath, [join(payload, "sidecar.cjs")], { - input: "not json\n", - encoding: "utf8", - windowsHide: true, - timeout: 20_000, - // Never discover the OpenCode service of the computer running the test. - env: { ...process.env, XDG_STATE_HOME: join(payload, "state") }, - }) - assert.equal(sidecar.status, 0, sidecar.stderr) - assert.deepEqual(JSON.parse(sidecar.stdout), { error: { message: "Invalid panel request." } }) + for (const entry of readStoredZip( + readFileSync(join(import.meta.dirname, "../plugin", marker.opencodeIntegration.host.payload)), + )) { + const file = join(payload, entry.name) + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, entry.data) + } + const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") const probe = spawnSync(python, ["-I", join(import.meta.dirname, "panel_probe.py"), payload], { encoding: "utf8", windowsHide: true, @@ -53,340 +27,3 @@ it("the installed panel runs its sidecar with Node: payload layout, Gaffer stubs rmSync(payload, { recursive: true, force: true }) } }) - -type Item = { type: string; data: Record } -type Input = { offerID: string; sessionID: string } -type Out = { id?: string; event?: string; error?: unknown; data: Record & { message?: string } } - -function fakeService() { - const calls: Array<[string, unknown]> = [] - const bindings = new Map() - const listeners = new Set<(item: Item) => void>() - let offers = [ - { offerID: "offer_other", label: "Gaffer: other.gfr", protocol: "ok" }, - { offerID: "offer_shot", label: "Gaffer: shot.gfr", protocol: "ok" }, - ] - let created = 0 - // The first calls of a Location OpenCode is still opening: the integration's RPC is not there yet. - let unavailable = 0 - const record = - (name: string, result: (input: Input) => unknown = () => ({})) => - async (input: Input) => { - calls.push([name, input]) - return result(input) - } - const rpc = new Proxy({} as Record, { - get: (_target, name: string) => { - const methods: Record unknown> = { - hosts: () => { - if (unavailable > 0) { - unavailable -= 1 - throw new Error("RPC is unavailable: neuralnomads.gaffer") - } - return { offers } - }, - attachHost: ({ offerID, sessionID }) => { - const bound = bindings.get(sessionID) - if (bound && bound !== offerID) return { outcome: "busy" } - bindings.set(sessionID, offerID) - return { outcome: "attached" } - }, - detachHost: ({ sessionID }) => ({ outcome: bindings.delete(sessionID) ? "detached" : "none" }), - bindingRead: ({ sessionID }) => - bindings.has(sessionID) - ? { state: "attached", binding: { offerID: bindings.get(sessionID), label: "x" } } - : { state: "none" }, - } - return record(`rpc.${name}`, methods[name] ?? (() => ({ outcome: "refused" }))) - }, - }) - const api = { - rpc: () => rpc, - session: { - list: record("session.list", () => ({ - data: [ - { id: "ses_archived", metadata: { [SCRIPT_MARKER]: KEY }, time: { archived: 1 } }, - { id: "ses_foreign", metadata: { [SCRIPT_MARKER]: "document:other" }, time: {} }, - { id: "ses_old", metadata: { [SCRIPT_MARKER]: KEY }, time: {} }, - ], - cursor: {}, - })), - create: record("session.create", () => ({ id: `ses_new${++created}` })), - prompt: record("session.prompt"), - interrupt: record("session.interrupt"), - switchModel: record("session.switchModel"), - active: record("session.active", () => ({})), - }, - message: { - list: record("message.list", () => ({ - data: [ - { type: "assistant", content: [{ type: "text", text: "Done." }] }, - { type: "user", text: "Add a sphere" }, - ], - })), - }, - model: { - list: record("model.list", () => ({ - data: [ - { id: "m1", providerID: "p", name: "M1", enabled: true }, - { id: "m2", providerID: "p", name: "M2", enabled: false }, - ], - })), - default: record("model.default", () => ({ data: { id: "m1", providerID: "p" } })), - }, - permission: { reply: record("permission.reply") }, - event: { - subscribe: ({ signal }: { signal: AbortSignal }) => - (async function* () { - const queue: Item[] = [] - let wake = () => {} - const listener = (item: Item) => { - queue.push(item) - wake() - } - listeners.add(listener) - signal.addEventListener("abort", () => wake(), { once: true }) - try { - while (!signal.aborted) { - const item = queue.shift() - if (item) yield item - else - await new Promise((resolve) => { - wake = resolve - }) - } - } finally { - listeners.delete(listener) - } - })(), - }, - } - return { - api: api as unknown as Api, - calls, - bindings, - setOffers: (next: typeof offers) => { - offers = next - }, - setUnavailable: (calls: number) => { - unavailable = calls - }, - push: async (item: Item) => { - for (const listener of listeners) listener(item) - await new Promise((resolve) => setImmediate(resolve)) - }, - } -} - -function harness(offerWaitMs = -1) { - const service = fakeService() - const out: Out[] = [] - const host: Array<[string, unknown]> = [] - const panel = createPanel({ - discover: async () => service.api, - send: (message) => out.push(message as Out), - requestHost: async (_endpoint, method, params) => { - host.push([method, params]) - return {} - }, - offerWaitMs, - checkEveryMs: 60_000, - }) - let id = 0 - const call = (method: string, params: Record = {}, channel = "panel") => - panel.dispatch({ id: String(++id), channel, method, params }) - const events = (name: string) => out.filter((message) => message.event === name).map((message) => message.data) - return { service, out, host, panel, call, events } -} - -it("Connect resumes the script's marked conversation and attaches it to that script's offer only", async () => { - const { service, host, panel, call, events } = harness() - try { - await call("connect", CONNECT) - assert.equal(service.calls.filter(([name]) => name === "session.create").length, 0) - assert.deepEqual(service.bindings, new Map([["ses_old", "offer_shot"]])) - assert.deepEqual(events("session")[0], { - id: "ses_old", - resumed: true, - model: "p/m1", - workspace: CONNECT.directory, - }) - assert.deepEqual(events("history")[0]?.messages, [ - { role: "user", text: "Add a sphere" }, - { role: "assistant", text: "Done." }, - ]) - assert.deepEqual(events("models")[0], { selected: "p/m1", models: [{ id: "m1", provider_id: "p", name: "M1" }] }) - assert.deepEqual(events("status").at(-1), { state: "idle" }) - - // Streaming: this conversation's events only. - await service.push({ type: "session.text.delta", data: { sessionID: "ses_other", delta: "no" } }) - await service.push({ type: "session.execution.started", data: { sessionID: "ses_old" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "Hel" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "lo" } }) - await service.push({ - type: "permission.asked", - data: { sessionID: "ses_old", id: "per_1", action: "gaffer_write" }, - }) - assert.deepEqual(events("assistant_delta"), [{ text: "Hel" }, { text: "lo" }]) - assert.deepEqual(events("status").at(-1), { state: "busy" }) - assert.deepEqual(events("permission"), [{ request_id: "per_1", action: "gaffer_write", resources: [] }]) - - await call("permission_reply", { request_id: "per_1", reply: "once" }) - await call("prompt", { text: "Add a light" }) - await call("switch_model", { model: "p/m1" }) - await call("interrupt") - const names = service.calls.map(([name]) => name) - assert.deepEqual(service.calls.find(([name]) => name === "permission.reply")?.[1], { - sessionID: "ses_old", - requestID: "per_1", - decision: "once", - }) - assert.deepEqual(service.calls.find(([name]) => name === "session.prompt")?.[1], { - sessionID: "ses_old", - text: "Add a light", - }) - assert.ok(names.includes("session.switchModel") && names.includes("session.interrupt")) - assert.deepEqual(host, [ - ["resume", { script_handle: "gaffer:shot", session_id: "ses_old" }], - ["cancel", { script_handle: "gaffer:shot", session_id: "ses_old" }], - ]) - - // New: another conversation, marked for the same script, on the same offer; the previous one is released. - await call("new_session", CONNECT) - const created = service.calls.find(([name]) => name === "session.create")?.[1] - assert.deepEqual(created, { - title: "Gaffer: shot.gfr", - location: { directory: CONNECT.directory }, - metadata: { [SCRIPT_MARKER]: KEY }, - }) - assert.deepEqual(service.bindings, new Map([["ses_new1", "offer_shot"]])) - assert.deepEqual(events("session").at(-1), { - id: "ses_new1", - resumed: false, - model: "p/m1", - workspace: CONNECT.directory, - }) - - // Close: this conversation only; the offer is never withdrawn and never announced by the panel. - await call("close") - assert.deepEqual(service.bindings, new Map()) - assert.deepEqual(host.at(-1), ["cancel", { script_handle: "gaffer:shot", session_id: "ses_new1" }]) - await call("prompt", { text: "late" }) - assert.equal(events("error").at(-1)?.message, "Choose Connect first.") - const rpcMethods = new Set(service.calls.map(([name]) => name).filter((name) => name.startsWith("rpc."))) - assert.deepEqual(rpcMethods, new Set(["rpc.hosts", "rpc.attachHost", "rpc.bindingRead", "rpc.detachHost"])) - } finally { - await panel.closeAll() - } -}) - -it("Connect refuses an ambiguous or absent offer, keeps a conversation attached elsewhere and hides SDK errors", async () => { - const { service, panel, call, events } = harness() - try { - service.setOffers([ - { offerID: "offer_a", label: "Gaffer: shot.gfr", protocol: "ok" }, - { offerID: "offer_b", label: "Gaffer: shot.gfr", protocol: "ok" }, - ]) - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /^Several scripts offer Gaffer: shot.gfr/) - service.setOffers([]) - await call("connect", CONNECT) - assert.equal(events("error").at(-1)?.message, "This script is not offered to OpenCode yet; choose Connect again.") - assert.equal(service.calls.filter(([name]) => name === "rpc.attachHost").length, 0) - - // The marked conversation is attached to another application: never taken from it. - service.setOffers([ - { offerID: "offer_shot", label: "Gaffer: shot.gfr", protocol: "ok" }, - { offerID: "offer_blender", label: "Blender: shot.blend", protocol: "ok" }, - ]) - service.bindings.set("ses_old", "offer_blender") - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /attached to another application/) - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - // Attached here, then moved elsewhere by another client: closing leaves that binding alone. - service.bindings.clear() - await call("connect", CONNECT) - service.bindings.set("ses_old", "offer_blender") - await call("close") - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - for (const bad of [{ token: "short" }, { host: "10.0.0.1" }, { offer_label: "" }]) { - await call("connect", { ...CONNECT, ...bad }) - assert.match( - String(events("error").at(-1)?.message), - /^The panel action failed: (Invalid host endpoint|Incomplete connect request)\. Check that OpenCode runs/, - ) - } - service.bindings.clear() - await call("connect", CONNECT) - ;(service.api.session as { prompt: unknown }).prompt = async () => { - throw new Error(`token ${HOST.token} on port ${HOST.port}`) - } - await call("prompt", { text: "x" }) - const message = events("error").at(-1)?.message as string - assert.ok(!message.includes(HOST.token) && !message.includes(String(HOST.port)), message) - } finally { - await panel.closeAll() - } -}) - -// Real trial: the first Connect failed while OpenCode opened the script's folder (its Location) and loaded its plugins -// ("RPC is unavailable"); it was read as the CodeNomad conversation attached to the same script holding it. -it("Connect waits for the Location OpenCode is still opening, next to a conversation attached to the same script", async () => { - const { service, panel, call, events } = harness(10_000) - try { - service.bindings.set("ses_codenomad", "offer_shot") - service.setUnavailable(2) - await call("connect", CONNECT) - assert.deepEqual(events("error"), []) - assert.equal(service.calls.filter(([name]) => name === "rpc.hosts").length, 3) - // Both conversations are attached to the script; closing the panel leaves the other one attached. - assert.deepEqual( - service.bindings, - new Map([ - ["ses_codenomad", "offer_shot"], - ["ses_old", "offer_shot"], - ]), - ) - await call("close") - assert.deepEqual(service.bindings, new Map([["ses_codenomad", "offer_shot"]])) - } finally { - await panel.closeAll() - } -}) - -it("a failed Connect says which step failed and why, without a credential", async () => { - const { service, panel, call, events } = harness(-1) - try { - service.setUnavailable(1) - await call("connect", CONNECT) - assert.equal( - events("error").at(-1)?.message, - "Connect failed while finding this script's offer: RPC is unavailable: neuralnomads.gaffer. Check that OpenCode runs, then choose Connect.", - ) - ;(service.api.session as { list: unknown }).list = async () => { - throw new Error(`refused by 127.0.0.1:${HOST.port} with Basic secret ${HOST.token}\nstack`) - } - await call("connect", CONNECT) - const message = String(events("error").at(-1)?.message) - assert.match( - message, - /^Connect failed while finding this script's conversation: refused by 127\.0\.0\.1:… with Basic …/, - ) - assert.ok( - !message.includes(HOST.token) && !message.includes(String(HOST.port)) && !message.includes("stack"), - message, - ) - } finally { - await panel.closeAll() - } -}) - -it("Connect without a running OpenCode says so", async () => { - const out: Out[] = [] - const panel = createPanel({ discover: async () => undefined, send: (message) => out.push(message as never) }) - await panel.dispatch({ id: "1", channel: "panel", method: "connect", params: CONNECT }) - assert.equal(out[0]?.data.message, "Start OpenCode before connecting the panel.") - assert.deepEqual(out[1], { id: "1", error: { message: "Panel action failed." } }) -}) diff --git a/integrations/gaffer/test/panel_probe.py b/integrations/gaffer/test/panel_probe.py index 33bda18..ccb10d8 100644 --- a/integrations/gaffer/test/panel_probe.py +++ b/integrations/gaffer/test/panel_probe.py @@ -3,7 +3,6 @@ Usage: python -I panel_probe.py """ import gc -import hashlib import pathlib import sys import types @@ -132,6 +131,10 @@ def emit(self, channel, name, data): api = Api() +api.__path__ = [] +api.panelServices = lambda: [] +service = types.ModuleType("GafferOpenCode.opencode_service") +service.panel_launcher = lambda results, override: (sys.executable, True) gaffer = types.ModuleType("Gaffer") gaffer.WeakMethod = weak_method gafferui = types.ModuleType("GafferUI") @@ -146,6 +149,7 @@ def emit(self, channel, name, data): "Gaffer": gaffer, "GafferUI": gafferui, "GafferOpenCode": api, + "GafferOpenCode.opencode_service": service, "IECore": MagicMock(), "imath": MagicMock(), "Qt": qt, @@ -174,47 +178,31 @@ def test_installed_client_runs_node_sidecar(self): self.assertEqual(Editor.registered, ("OpenCode for Gaffer", GafferOpenCodeUI.OpenCodeEditor)) process = qt.QtCore.QProcess.return_value process.state.return_value = qt.QtCore.QProcess.NotRunning - with patch.dict("os.environ", {"NEURALNOMADS_GAFFER_NODE": ""}), patch.object( - client_module.shutil, "which", return_value="/usr/bin/node" - ) as which: - client_module.ClientProcess() - which.assert_called_with("node") - process.setProgram.assert_called_with("/usr/bin/node") + client = client_module.ClientProcess() + client.send("trial", "connect", {}) + process.setProgram.assert_called_with(sys.executable) + qt.QtCore.QProcessEnvironment.systemEnvironment.return_value.insert.assert_called_with("BUN_BE_BUN", "1") process.setArguments.assert_called_with([str(PAYLOAD / "sidecar.cjs")]) process.start.assert_called() self.assertTrue((PAYLOAD / "sidecar.cjs").is_file()) - # NEURALNOMADS_GAFFER_NODE names Node explicitly. - with patch.dict("os.environ", {"NEURALNOMADS_GAFFER_NODE": "/opt/node22/bin/node"}): - client_module.ClientProcess() - process.setProgram.assert_called_with("/opt/node22/bin/node") def test_connect_targets_this_scripts_offer_and_closing_never_withdraws(self): shot = pathlib.Path(PAYLOAD / "shots" / "shot.gfr") script = Script("gaffer:shot", str(shot)) api.offers[script.handle] = {"label": "Gaffer: shot.gfr", "offer_key": "gaffer-shot", "advertising": True} editor = GafferOpenCodeUI.OpenCodeEditor(script) - # Opening the panel attaches nothing: Gaffer already offers the script by itself. - self.assertEqual(api.calls, []) - self.assertEqual(self.client.sent, []) - - private(editor, "toggleConnection")() channel, method, params = self.client.sent[-1] self.assertEqual(api.calls, [("acquire", channel)]) self.assertEqual(method, "connect") - key = "document:" + hashlib.sha256(str(shot.resolve()).encode("utf-8")).hexdigest() self.assertEqual( params, { **HOST, "script_handle": "gaffer:shot", "offer_label": "Gaffer: shot.gfr", - "script_key": key, - "script_name": "shot.gfr", "directory": str(shot.resolve().parent), }, ) - self.client.emit(channel, "session", {"id": "ses_shot", "resumed": True}) - self.client.emit(channel, "status", {"state": "idle"}) prompt = private(editor, "prompt") prompt.getText.return_value = "Add a sphere" private(editor, "send")(None) @@ -224,28 +212,14 @@ def test_connect_targets_this_scripts_offer_and_closing_never_withdraws(self): private(editor, "newSession")(None) self.assertEqual(self.client.sent[-1], (channel, "new_session", params)) - # Disconnect releases the panel's conversation only. - private(editor, "toggleConnection")() - self.assertEqual(self.client.sent[-1], (channel, "close", {})) - self.assertEqual(api.calls[-1], ("release", channel)) - # A reply to the closed connection is ignored. - self.client.emit(channel, "session", {"id": "ses_late"}) - self.assertFalse(private(editor, "connected")) - - # Connect again asks for the same script's conversation: the sidecar resumes the session marked with it. - private(editor, "toggleConnection")() - self.assertEqual(self.client.sent[-1], (channel, "connect", params)) - - # Save As: another file is another script's conversation. + # Save As updates the offer but keeps the same folder. moved = PAYLOAD / "shots" / "shot_v2.gfr" api.offers[script.handle]["label"] = "Gaffer: shot_v2.gfr" script.setFileName(str(moved)) - self.assertEqual(self.client.sent[-1], (channel, "close", {})) - self.assertEqual(api.calls[-1], ("release", channel)) - private(editor, "toggleConnection")() + self.assertEqual(self.client.sent[-1][1], "connect") moved_params = self.client.sent[-1][2] self.assertEqual(moved_params["offer_label"], "Gaffer: shot_v2.gfr") - self.assertNotEqual(moved_params["script_key"], key) + self.assertEqual(moved_params["directory"], params["directory"]) # Closing the editor (its last reference gone) releases its conversation and the panel registration. del editor, prompt @@ -260,16 +234,13 @@ def test_each_script_has_its_own_offer_and_conversation(self): api.offers[first.handle] = {"label": "Gaffer: untitled", "offer_key": "gaffer-one", "advertising": True} api.offers[second.handle] = {"label": "Gaffer: untitled (2)", "offer_key": "gaffer-two", "advertising": True} editors = [GafferOpenCodeUI.OpenCodeEditor(first), GafferOpenCodeUI.OpenCodeEditor(second)] - for editor in editors: - private(editor, "toggleConnection")() (a, _, one), (b, _, two) = self.client.sent self.assertNotEqual(a, b) - self.assertEqual((one["offer_label"], one["script_key"]), ("Gaffer: untitled", "untitled:gaffer:one")) - self.assertEqual((two["offer_label"], two["script_key"]), ("Gaffer: untitled (2)", "untitled:gaffer:two")) + self.assertEqual(one["offer_label"], "Gaffer: untitled") + self.assertEqual(two["offer_label"], "Gaffer: untitled (2)") # A second panel on the same script takes back the same conversation. third = GafferOpenCodeUI.OpenCodeEditor(first) - private(third, "toggleConnection")() - self.assertEqual(self.client.sent[-1][2]["script_key"], "untitled:gaffer:one") + self.assertEqual(self.client.sent[-1][2]["directory"], one["directory"]) # Closing one panel leaves the others (and every offer) alone. del third gc.collect() @@ -277,17 +248,14 @@ def test_each_script_has_its_own_offer_and_conversation(self): self.assertEqual(api.calls[-1], ("release", "channel-2")) self.assertEqual([call for call in api.calls if call[0] == "release"], [("release", "channel-2")]) - def test_a_script_not_offered_is_said_without_connecting(self): + def test_a_missing_offer_is_left_to_the_shared_sidecar(self): script = Script("gaffer:private") api.offers[script.handle] = {"label": "Gaffer: untitled", "offer_key": "gaffer-private", "advertising": False} editor = GafferOpenCodeUI.OpenCodeEditor(script) append = MagicMock() setattr(editor, "_OpenCodeEditor__append", append) - private(editor, "toggleConnection")() - self.assertEqual(self.client.sent, []) - self.assertEqual(api.calls, []) - append.assert_called_once_with("error", "OpenCode Link does not offer this script to OpenCode.") - self.assertFalse(private(editor, "active")) + self.assertEqual(self.client.sent[0][1], "connect") + append.assert_not_called() if __name__ == "__main__": diff --git a/integrations/godot/host/addons/opencode_link/dock.gd b/integrations/godot/host/addons/opencode_link/dock.gd index 193d24a..235ba37 100644 --- a/integrations/godot/host/addons/opencode_link/dock.gd +++ b/integrations/godot/host/addons/opencode_link/dock.gd @@ -1,9 +1,7 @@ @tool extends VBoxContainer ## The OpenCode dock: this project's conversation inside the editor. A plain client of the OpenCode service through a -## Node sidecar (sidecar.cjs, beside this file; Node on PATH, or NEURALNOMADS_GODOT_NODE): Godot offers its project -## by itself (link.gd), the dock only attaches its own conversation to that offer, and Disconnect (or closing the -## editor) releases that conversation only. Other conversations attached to the same project stay attached. +## Private sidecar: Godot offers its project (link.gd), and this dock attaches the current folder's conversation. var link: RefCounted @@ -12,6 +10,12 @@ var _stdio: FileAccess var _stderr: FileAccess var _buffer := PackedByteArray() var _channel := "" +var _target := {} +var _pending: Array[Dictionary] = [] +var _selected := "" +var _draft := false +var _retry_at := 0 +var _problem := "" var _next := 0 var _active := false var _connected := false @@ -25,8 +29,7 @@ var _session_label := Label.new() var _status_label := Label.new() var _agent_label := Label.new() var _model_button := OptionButton.new() -var _new_button := Button.new() -var _connect_button := Button.new() +var _conversations := OptionButton.new() var _transcript := RichTextLabel.new() var _permission_row := HBoxContainer.new() var _permission_label := Label.new() @@ -37,19 +40,15 @@ var _stop_button := Button.new() func _ready() -> void: _channel = "dock-" + Crypto.new().generate_random_bytes(8).hex_encode() - visibility_changed.connect(func(): - if _active and not is_visible_in_tree(): - disconnect_dock() - ) var header := HBoxContainer.new() var brand := Label.new() brand.text = "OpenCode" header.add_child(brand) - _session_label.text = "disconnected" + _session_label.text = "" _session_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL _session_label.clip_text = true header.add_child(_session_label) - _status_label.text = "DISCONNECTED" + _status_label.text = "CONNECTING" header.add_child(_status_label) add_child(header) @@ -61,13 +60,19 @@ func _ready() -> void: _model_button.clip_text = true _model_button.item_selected.connect(_select_model) row.add_child(_model_button) - _new_button.text = "New" - _new_button.disabled = true - _new_button.pressed.connect(func(): _connect("new_session")) - row.add_child(_new_button) - _connect_button.text = "Connect" - _connect_button.pressed.connect(toggle_connection) - row.add_child(_connect_button) + _conversations.clip_text = true + _conversations.size_flags_horizontal = Control.SIZE_EXPAND_FILL + _conversations.add_item("New conversation") + _conversations.set_item_metadata(0, "") + _conversations.get_popup().about_to_popup.connect(func(): _send("list", {})) + _conversations.item_selected.connect(func(index: int): + var id: String = _conversations.get_item_metadata(index) + if id == "": + _send("new_session", _target) + else: + _send("open", {"session_id": id}) + ) + row.add_child(_conversations) add_child(row) _transcript.size_flags_vertical = Control.SIZE_EXPAND_FILL @@ -103,15 +108,12 @@ func _ready() -> void: _stop_button.pressed.connect(stop) buttons.add_child(_stop_button) _send_button.text = "Send" - _send_button.disabled = true _send_button.pressed.connect(func(): send_text(_prompt.text)) buttons.add_child(_send_button) add_child(buttons) func _exit_tree() -> void: - if _active: - disconnect_dock() if _stdio != null: # The sidecar ends once its input closes, after releasing its conversations. _stdio.close() @@ -120,19 +122,11 @@ func _exit_tree() -> void: # --- what a user (or a script driving the dock) does --- -func toggle_connection() -> void: - if _active: - disconnect_dock() - else: - _connect("connect") - - func send_text(text: String) -> void: text = text.strip_edges() - if _busy or not _connected or text == "": + if _busy or text == "": return _prompt.text = "" - _append("user", text) _send("prompt", {"text": text}) @@ -140,20 +134,6 @@ func stop() -> void: _send("interrupt", {}) -func disconnect_dock() -> void: - _active = false - _connected = false - _send("close", {}) - _connect_button.text = "Connect" - _status_label.text = "DISCONNECTED" - _permission = "" - _permission_row.hide() - _streaming = false - _set_busy(false) - _new_button.disabled = true - _model_button.disabled = true - - func transcript() -> String: return _transcript.get_parsed_text() @@ -166,7 +146,7 @@ func state() -> Dictionary: static func _node() -> String: var configured := OS.get_environment("NEURALNOMADS_GODOT_NODE") - if configured != "": + if configured != "" and FileAccess.file_exists(configured): return configured var windows := OS.get_name() == "Windows" for directory in OS.get_environment("PATH").split(";" if windows else ":", false): @@ -176,32 +156,65 @@ static func _node() -> String: return "" -func _start() -> bool: - if _pid > 0 and OS.is_process_running(_pid): - return true - var node := _node() - if node == "": - _append("error", "Install Node.js 22 or later, or set NEURALNOMADS_GODOT_NODE.") - return false +func _start() -> void: + var services: Array = link.advertiser_results() + var runtime := "" + for result in services: + var advertised: String = result.get("panel_runtime", "") + if advertised.is_absolute_path() and FileAccess.file_exists(advertised): + runtime = advertised + break + var bun := runtime != "" + if not bun: + runtime = _node() var sidecar := ProjectSettings.globalize_path(get_script().resource_path.get_base_dir().path_join("sidecar.cjs")) if not FileAccess.file_exists(sidecar): - _append("error", "The OpenCode dock's sidecar is missing: install OpenCode Link again (godot_install_host).") - return false - var started := OS.execute_with_pipe(node, [sidecar], false) + _blocked("The OpenCode dock's sidecar is missing: install OpenCode Link again (godot_install_host).") + return + if runtime == "": + if not services.is_empty(): + _blocked("No OpenCode runtime, NEURALNOMADS_GODOT_NODE executable, or Node on PATH.") + return + var inherited := OS.get_environment("BUN_BE_BUN") + var had_inherited := OS.has_environment("BUN_BE_BUN") + if bun: + OS.set_environment("BUN_BE_BUN", "1") + else: + OS.unset_environment("BUN_BE_BUN") + var started := OS.execute_with_pipe(runtime, [sidecar], false) + if had_inherited: + OS.set_environment("BUN_BE_BUN", inherited) + else: + OS.unset_environment("BUN_BE_BUN") if started.is_empty(): - _append("error", "Node.js did not start: %s" % node) - return false + _blocked("The OpenCode sidecar runtime did not start.") + return _pid = started.pid _stdio = started.stdio _stderr = started.stderr _buffer = PackedByteArray() - return true + _problem = "" + var params := _target.duplicate() + params.session_id = _selected + params.draft = _draft + _send("connect", params) + for item in _pending: + _send(item.method, item.params) + _pending.clear() + + +func _blocked(message: String) -> void: + if message != _problem: + _problem = message + _event("error", {"message": message}) func _send(method: String, params: Dictionary) -> void: - if method == "close" and (_stdio == null or not OS.is_process_running(_pid)): - return - if not _start(): + if _stdio == null or not OS.is_process_running(_pid): + if method == "interrupt": + _pending.clear() + elif method == "prompt": + _pending.append({"method": method, "params": params}) return _next += 1 var line := JSON.stringify({"id": str(_next), "channel": _channel, "method": method, "params": params}) + "\n" @@ -209,7 +222,15 @@ func _send(method: String, params: Dictionary) -> void: func _process(_delta: float) -> void: + if not _active: + if not is_visible_in_tree(): + return + _active = true + _sync() if _stdio == null: + if Time.get_ticks_msec() >= _retry_at: + _retry_at = Time.get_ticks_msec() + 1000 + _start() return var available := _stdio.get_length() if available > 0: @@ -225,7 +246,7 @@ func _process(_delta: float) -> void: var message: Dictionary = parser.data if message.get("channel") == _channel and message.get("event") is String: _event(message.event, message.get("data", {}) if message.get("data") is Dictionary else {}) - elif message.get("error") is Dictionary and message.get("channel") == null: + elif message.get("error") is Dictionary and not message.has("id"): _event("error", message.error) if _stderr != null and _stderr.get_length() > 0: _stderr.get_buffer(_stderr.get_length()) @@ -233,30 +254,30 @@ func _process(_delta: float) -> void: _stdio = null _stderr = null _pid = -1 - if _active: - _event("error", {"message": "The OpenCode sidecar stopped; choose Connect to start it again."}) + _event("status", {"state": "connecting"}) -func _connect(method: String) -> void: - if link == null or not link.advertising(): - _append("error", "OpenCode Link does not offer this project to OpenCode (OPENCODE_GODOT_OFFER=0?).") +func _sync() -> void: + if link == null or not _active: return var project: String = link.project_dir() + var scene := EditorInterface.get_edited_scene_root() + var directory := project + if scene != null and scene.scene_file_path.begins_with("res://"): + directory = link.native(ProjectSettings.globalize_path(scene.scene_file_path).get_base_dir()) var params: Dictionary = link.info() params.merge({ "script_handle": link.script_handle, "offer_label": link.label(), - "project_key": "project:" + project.to_lower().replace("\\", "/").sha256_text(), - "project_name": link.project_name(), - "directory": project, + "directory": directory, }) - _active = true - _connected = false - _connect_button.text = "Disconnect" - _new_button.disabled = false - _status_label.text = "CONNECTING" - _send_button.disabled = true - _send(method, params) + if params != _target: + if directory != _target.get("directory"): + _selected = "" + _draft = false + _pending.clear() + _target = params + _send("connect", params) func _select_model(index: int) -> void: @@ -282,8 +303,8 @@ func _reply_permission(reply: String) -> void: func _set_busy(busy: bool) -> void: _busy = busy - _stop_button.disabled = not busy - _send_button.disabled = not _connected or busy + _stop_button.disabled = not busy and _status_label.text != "CONNECTING" + _send_button.disabled = busy _prompt.editable = not busy _model_button.disabled = not _connected or busy or _models.is_empty() @@ -307,11 +328,28 @@ func _event(name: String, data: Dictionary) -> void: match name: "session": _connected = true - _session_label.text = "session " + str(data.get("id", "")).right(8) + _selected = str(data.id) if data.get("id") else "" + _draft = data.get("draft", false) + _session_label.text = "Session " + _selected.right(8) if _selected != "" else "New conversation" _session_label.tooltip_text = "Workspace: " + str(data.get("workspace", "")) _agent_label.text = str(data.get("agent", "")) if data.get("agent") else "default agent" _set_model(str(data.get("model", ""))) - _append("system", "Resumed conversation" if data.get("resumed") else "New conversation") + "conversations": + _conversations.clear() + _conversations.add_item("New conversation") + _conversations.set_item_metadata(0, "") + var index := 0 + for item in data.get("entries", []): + var title: String = item.get("title", "") + _conversations.add_item(title if title != "" else "Untitled") + _conversations.set_item_metadata(_conversations.item_count - 1, item.id) + if item.id == _selected: + index = _conversations.item_count - 1 + _conversations.select(index) + "notice": + _append("system", data.message) + "user_message": + _append("user", data.text) "models": _models = data.get("models", []) _model_button.clear() @@ -348,6 +386,10 @@ func _event(name: String, data: Dictionary) -> void: "status": var value := str(data.get("state", "unknown")) _status_label.text = value.to_upper() + if value == "connecting": + _connected = false + _permission = "" + _permission_row.hide() _set_busy(value in ["busy", "retry"]) "error": _append("error", str(data.get("message", "Unknown OpenCode error"))) diff --git a/integrations/godot/host/addons/opencode_link/plugin.gd b/integrations/godot/host/addons/opencode_link/plugin.gd index 511238b..528e9ac 100644 --- a/integrations/godot/host/addons/opencode_link/plugin.gd +++ b/integrations/godot/host/addons/opencode_link/plugin.gd @@ -41,6 +41,8 @@ func _scene_changed(_value: Variant = null) -> void: if link != null: link.refresh_label() link.bump() + if dock != null: + dock._sync() func _process(_delta: float) -> void: diff --git a/integrations/godot/host/addons/opencode_link/service.gd b/integrations/godot/host/addons/opencode_link/service.gd index b76fa3d..7434ba1 100644 --- a/integrations/godot/host/addons/opencode_link/service.gd +++ b/integrations/godot/host/addons/opencode_link/service.gd @@ -247,6 +247,16 @@ func advertise_once() -> Variant: return results +static func _advertise_result(service: String, label: String, answer: Array) -> Dictionary: + var said := outcome("advertise", answer[0], answer[1]) + var result := {"service": service, "label": label, "outcome": said} + if said in ["accepted", "renewed"]: + var runtime: Variant = answer[1].output.get("panel_runtime") + if runtime is String and runtime.is_absolute_path(): + result.panel_runtime = runtime + return result + + func _renew(offers: Array, project: String) -> Array: _count += 1 var results := [] @@ -256,9 +266,9 @@ func _renew(offers: Array, project: String) -> Array: var target: Array = _targets[name] for offer in offers: var answer := call_rpc(target[0], "advertise", offer, target[1], RENEW_TIMEOUT_MS) - var said := outcome("advertise", answer[0], answer[1]) - results.append({"service": name, "label": offer.label, "outcome": said}) - failed = failed or not said in ["accepted", "renewed"] + var result := _advertise_result(name, offer.label, answer) + results.append(result) + failed = failed or not result.outcome in ["accepted", "renewed"] if not failed: return results var found := {} @@ -273,12 +283,12 @@ func _renew(offers: Array, project: String) -> Array: reached = true var taken := false for offer in offers: - var said := "error" + var sent := [500, null] if answer[0] == 200: - var sent := call_rpc(service, "advertise", offer, directory, maxi(500, deadline - Time.get_ticks_msec())) - said = outcome("advertise", sent[0], sent[1]) - results.append({"service": service.file, "label": offer.label, "outcome": said}) - taken = taken or said in ["accepted", "renewed"] + sent = call_rpc(service, "advertise", offer, directory, maxi(500, deadline - Time.get_ticks_msec())) + var result := _advertise_result(service.file, offer.label, sent) + results.append(result) + taken = taken or result.outcome in ["accepted", "renewed"] if taken: found[service.file] = [service, directory] break diff --git a/integrations/godot/plugin/README.md b/integrations/godot/plugin/README.md index 123183c..382e4e1 100644 --- a/integrations/godot/plugin/README.md +++ b/integrations/godot/plugin/README.md @@ -1,6 +1,6 @@ # OpenCode for Godot (preview) -Read, edit and check the project open in Godot from an OpenCode conversation. Requires Godot 4.7 or later in the 4.x series and OpenCode 2.2 or later. The optional editor dock needs Node.js 22 or later; discovery and the editor tools do not. +Read, edit and check the project open in Godot from an OpenCode conversation. Requires Godot 4.7 or later in the 4.x series and OpenCode 2.2 or later. ## Install @@ -31,9 +31,9 @@ Edits to scene-owned nodes and stored properties are grouped into one undo actio ## Editor dock -Open **OpenCode** and select **Connect**. It creates or resumes the project conversation and displays the agent, model, streamed replies and tool calls. Use **Stop** to interrupt a response and **Disconnect** to release the dock's attachment. You can connect an independent OpenCode conversation to the same editor. Duplicate offer labels are refused by the dock rather than choosing an editor arbitrarily. +Open the **OpenCode** dock. It automatically resumes the latest conversation in the scene’s folder, or the project folder when no saved scene is open. Open another scene in the same folder to keep the selected conversation. The selector lists the folder’s conversations; **New conversation** creates nothing until you send a message. Use **Stop** to interrupt or clear queued prompts. -The add-on handles discovery and editor requests in GDScript using the local offer protocol. The dock starts a Node client over private pipes, using OpenCode's SDK for sessions and events, following Gaffer's panel. Node is found on `PATH` or via `NEURALNOMADS_GODOT_NODE`. The dock never starts OpenCode. Set `OPENCODE_GODOT_OFFER=0` in the editor environment to disable advertising. +The dock uses OpenCode’s executable. Node.js 22+ (`NEURALNOMADS_GODOT_NODE` or `PATH`) is only a fallback. The dock never starts the OpenCode service. Set `OPENCODE_GODOT_OFFER=0` to disable advertising. ## Tests diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index 01d8ec947a1f95bd782bd8e4502bf01e58af5be2..7c435d1d55baef5f08afab977435b1e76d1f908c 100644 GIT binary patch delta 13091 zcmb7LdvqMtdG}rmBgrv1wk+GSY_1l8W^H*S8OH%RMmBFw06Vc=2$HfM?T)O$tKH4a ztb{5nYaXV-ZpdR}ZWAaPnwR&uP+>o~D1~B+W_Mq<^GM z`}^)=c4j3E)xpxt-0$A|-S7GPz8OxRUisFyR(^e|skM3kPkJ8OwQSi#yJ{zz7A`;F zds9y6^1#cxImfSk@{*35xK;3q$Lyo|OfPqec^*!90ne9m$G8)QPHw^t@W|!4itoF{ zkdK!NdDrg=c&=2Oa{a&wy;8CE@QP1YL&rbrhJ0`jpPg%+a(tdGyT!a$JUYnt`MxtV ze3O?WV#l8u<$L(>s3Hp7f}0E7JWWie)w8_sjLVhAokHNMXTBTyGg(JI?$_)4rLlrL zsb+0P=uTScyWHu7Fw&XE>2~0Tk~ll*hECoI9jm_=hh0nv z0cOjka;0o#Y-g-g3A15IJ+Nv2A|z#vSBg0+Gsv?6#A~GsUJ#~xA@j`Q<%mI$DFM@& z>kD|rynFv3_ljX=u(hRy^yTFT`N7bK#vq2I0PLe~?TV|~tDyA8LCE)zvS?z9W~1m% z<0=TCU~rRF#sH35Txc*(Sb|j$ziCaK_3~-(k)H!G{_{)IQntAXuaLKrTx8~7Teaqr zT4l}Z+Rra$^dv5C#^QBI)>*V(3k}+Du!< zOL!zHAVVIlrbQVo6Bns}v!sVCLn~c&if$pR7lk~eHIQ)YQ*AHEI%7epPzl{^*$F4C zj6T_hi8_^3UyI>xPi#JEXUunGZ$T3JtGK0{6v6OeMOzi_5 zUu+&LARM@PtM;=F_fRWMiRg?O=w*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5z zqW{iep}#nA@XzGAG|L-Q9MCX>u=_p`nUXuGSKKA@ydavG*i13mNeoNwLX1ZDz+Nw6 z7WrSx+Ahs>Xo}j#R^JbIu$S+LrmDQj20NqPG=sH)8f@_~kS`&foLo5c=VR5)+W1O? zyZel`HV>ohqGNDjg=sV+khuCNp3Y#A7{NeglgHpQxrT2+g~U!h0p(3G9v}wnG^u3_ z5G_Wq6JksfK8+;WQ@yu?L``ghw!&z6I(QhWWsreEVLue)(iog8eAJ;7$a z3sr6TpCrc4BsoZ8dJ%diIdl?UK!q-IsGJEzrV6vSLL-X=DeUstP%l17C zL+tm*p}Pb#w2l4fVVGc-J_6g>2e-rW+*clfGN~%;YW8%YS;F2>{N2;V?t2v0E{d>+ zl|2sYazA_&-YRBek3k8$_8Ztsy)py4*;CC@Rqo2iVN7CsPr!MV+(8XtRV%~?cKUv( zWaE!QS?h$3V_<{<=gO(@S~M{6O3AkT2z{+hns{7_To8`oBB6TD}-jcZ_2wD}EmKu#?ZD=+FHG*0;p2AfdP+^zx48hAehV8xak4 zY~!qac(W5ffwf!XY~-&p^1v$k9gN{LnlZZOiRs`>VoZAhs@SHNKxMx?0o6+z=4M%y z+h|p#+&O=U%$Tl+@RGahC8(7){FkZ99(@^ZT^UB1n3%U)Rx*rn)_M{)Gy5dG!4`Kz zbuRUDNG@hydjq!QUVj54W3{%=F>O^*TAGPDI_9{(c)O57Q;y_5eiKMZZrfWhF0tgz z7#lNh!+jE)c^ax$oTc(hPea`Tkyq@h(@?!3kB(?(w6uox>KsPr*(*-6(i~jS5Z00C z2A{jmVzV^|H8p3h=6OxBk2;_)(VxG9h$|vWph`%b{q;1YntJ=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "0713e18ccbe77151eb7ed563e87385a503e913f2310e6ae7a1072efd34d7af92" + "sha256": "55c09574c964661781b4e738f5fc33c694c07aba48f16f26e7ad1e01699565a8" } } } diff --git a/integrations/godot/plugin/src/sidecar-core.ts b/integrations/godot/plugin/src/sidecar-core.ts index c6ab5cf..251d504 100644 --- a/integrations/godot/plugin/src/sidecar-core.ts +++ b/integrations/godot/plugin/src/sidecar-core.ts @@ -6,15 +6,10 @@ import { export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" -export const PROJECT_MARKER = "opencode_godot_project" export const panelHost = { app: "Godot", rpcID: "neuralnomads.godot", - marker: PROJECT_MARKER, document: "project", - keyField: "project_key", - nameField: "project_name", - defaultName: "project", duplicateOffer: "Godot editors", agent: true, } satisfies PanelHost diff --git a/integrations/godot/test/godot.test.ts b/integrations/godot/test/godot.test.ts index 1469f8e..0fcbbbe 100644 --- a/integrations/godot/test/godot.test.ts +++ b/integrations/godot/test/godot.test.ts @@ -224,9 +224,9 @@ describe("OpenCode Link in a real Godot editor", { skip: !godot, concurrency: fa assert.match(crash.crash, /Program crashed/) }) - it("the dock reaches its sidecar (Node) from the editor", async () => { + it("the visible dock starts its sidecar automatically", async () => { await code( - 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.toggle_connection()', + 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.show()', ) const transcript = await until( async () => { @@ -234,12 +234,12 @@ describe("OpenCode Link in a real Godot editor", { skip: !godot, concurrency: fa 'result.text = EditorInterface.get_base_control().find_child("OpenCode", true, false).transcript()', { read_only: true }, ) - return /Connect failed|Start OpenCode/.test(read.result.text) ? read.result.text : "" + return /Could not connect|Start OpenCode/.test(read.result.text) ? read.result.text : "" }, 30_000, "the dock's answer", ) - assert.match(transcript, /Connect failed while finding this project's conversation|Start OpenCode/) + assert.match(transcript, /Could not connect|Start OpenCode/) }) it("says that the editor crashed, with its log", async () => { diff --git a/integrations/godot/test/panel.test.ts b/integrations/godot/test/panel.test.ts deleted file mode 100644 index 1c70871..0000000 --- a/integrations/godot/test/panel.test.ts +++ /dev/null @@ -1,386 +0,0 @@ -import assert from "node:assert/strict" -import { spawnSync } from "node:child_process" -import { mkdtempSync, rmSync } from "node:fs" -import { tmpdir } from "node:os" -import { join } from "node:path" -import { it } from "node:test" -import { build } from "esbuild" -import { type Api, createPanel, PROJECT_MARKER } from "../plugin/src/sidecar-core.ts" - -const KEY = "project:trial" -const HOST = { host: "127.0.0.1", port: 4242, token: "a".repeat(64) } -const CONNECT = { - ...HOST, - protocol: 1, - script_handle: "godot:1:trial", - offer_label: "Godot: Trial — main.tscn", - project_key: KEY, - project_name: "Trial", - directory: join(tmpdir(), "godot-trial"), -} - -it("the add-on's sidecar runs with Node as the add-on ships it", async () => { - const folder = mkdtempSync(join(tmpdir(), "godot-dock-")) - try { - await build({ - entryPoints: [join(import.meta.dirname, "..", "plugin", "src", "sidecar.ts")], - bundle: true, - format: "cjs", - platform: "node", - target: "node22", - outfile: join(folder, "sidecar.cjs"), - logLevel: "warning", - }) - const sidecar = spawnSync(process.execPath, [join(folder, "sidecar.cjs")], { - input: "not json\n", - encoding: "utf8", - windowsHide: true, - timeout: 20_000, - // Never discover the OpenCode service of the computer running the test. - env: { ...process.env, XDG_STATE_HOME: join(folder, "state") }, - }) - assert.equal(sidecar.status, 0, sidecar.stderr) - assert.deepEqual(JSON.parse(sidecar.stdout), { error: { message: "Invalid panel request." } }) - } finally { - rmSync(folder, { recursive: true, force: true }) - } -}) - -type Item = { type: string; data: Record } -type Input = { offerID: string; sessionID: string } -type Out = { id?: string; event?: string; error?: unknown; data: Record & { message?: string } } - -function fakeService() { - const calls: Array<[string, unknown]> = [] - const bindings = new Map() - const listeners = new Set<(item: Item) => void>() - let offers = [ - { offerID: "offer_other", label: "Godot: Other — main.tscn", protocol: "ok" }, - { offerID: "offer_trial", label: "Godot: Trial — main.tscn", protocol: "ok" }, - ] - let created = 0 - // The first calls of a Location OpenCode is still opening: the integration's RPC is not there yet. - let unavailable = 0 - const record = - (name: string, result: (input: Input) => unknown = () => ({})) => - async (input: Input) => { - calls.push([name, input]) - return result(input) - } - const rpc = new Proxy({} as Record, { - get: (_target, name: string) => { - const methods: Record unknown> = { - hosts: () => { - if (unavailable > 0) { - unavailable -= 1 - throw new Error("RPC is unavailable: neuralnomads.godot") - } - return { offers } - }, - attachHost: ({ offerID, sessionID }) => { - const bound = bindings.get(sessionID) - if (bound && bound !== offerID) return { outcome: "busy" } - bindings.set(sessionID, offerID) - return { outcome: "attached" } - }, - detachHost: ({ sessionID }) => ({ outcome: bindings.delete(sessionID) ? "detached" : "none" }), - bindingRead: ({ sessionID }) => - bindings.has(sessionID) - ? { state: "attached", binding: { offerID: bindings.get(sessionID), label: "x" } } - : { state: "none" }, - } - return record(`rpc.${name}`, methods[name] ?? (() => ({ outcome: "refused" }))) - }, - }) - const api = { - rpc: () => rpc, - session: { - list: record("session.list", () => ({ - data: [ - { id: "ses_archived", metadata: { [PROJECT_MARKER]: KEY }, time: { archived: 1 } }, - { id: "ses_foreign", metadata: { [PROJECT_MARKER]: "project:other" }, time: {} }, - { id: "ses_old", metadata: { [PROJECT_MARKER]: KEY }, time: {} }, - ], - cursor: {}, - })), - create: record("session.create", () => ({ id: `ses_new${++created}` })), - prompt: record("session.prompt"), - interrupt: record("session.interrupt"), - switchModel: record("session.switchModel"), - active: record("session.active", () => ({})), - }, - message: { - list: record("message.list", () => ({ - data: [ - { type: "assistant", content: [{ type: "text", text: "Done." }] }, - { type: "user", text: "Add a sphere" }, - ], - })), - }, - model: { - list: record("model.list", () => ({ - data: [ - { id: "m1", providerID: "p", name: "M1", enabled: true }, - { id: "m2", providerID: "p", name: "M2", enabled: false }, - ], - })), - default: record("model.default", () => ({ data: { id: "m1", providerID: "p" } })), - }, - permission: { reply: record("permission.reply") }, - event: { - subscribe: ({ signal }: { signal: AbortSignal }) => - (async function* () { - const queue: Item[] = [] - let wake = () => {} - const listener = (item: Item) => { - queue.push(item) - wake() - } - listeners.add(listener) - signal.addEventListener("abort", () => wake(), { once: true }) - try { - while (!signal.aborted) { - const item = queue.shift() - if (item) yield item - else - await new Promise((resolve) => { - wake = resolve - }) - } - } finally { - listeners.delete(listener) - } - })(), - }, - } - return { - api: api as unknown as Api, - calls, - bindings, - setOffers: (next: typeof offers) => { - offers = next - }, - setUnavailable: (calls: number) => { - unavailable = calls - }, - push: async (item: Item) => { - for (const listener of listeners) listener(item) - await new Promise((resolve) => setImmediate(resolve)) - }, - } -} - -function harness(offerWaitMs = -1) { - const service = fakeService() - const out: Out[] = [] - const host: Array<[string, unknown]> = [] - const panel = createPanel({ - discover: async () => service.api, - send: (message) => out.push(message as Out), - requestHost: async (_endpoint, method, params) => { - host.push([method, params]) - return {} - }, - offerWaitMs, - checkEveryMs: 60_000, - }) - let id = 0 - const call = (method: string, params: Record = {}, channel = "panel") => - panel.dispatch({ id: String(++id), channel, method, params }) - const events = (name: string) => out.filter((message) => message.event === name).map((message) => message.data) - return { service, out, host, panel, call, events } -} - -it("Connect resumes the project's marked conversation and attaches it to that project's offer only", async () => { - const { service, host, panel, call, events } = harness() - try { - await call("connect", CONNECT) - assert.equal(service.calls.filter(([name]) => name === "session.create").length, 0) - assert.deepEqual(service.bindings, new Map([["ses_old", "offer_trial"]])) - assert.deepEqual(events("session")[0], { - id: "ses_old", - resumed: true, - model: "p/m1", - agent: null, - workspace: CONNECT.directory, - }) - assert.deepEqual(events("history")[0]?.messages, [ - { role: "user", text: "Add a sphere" }, - { role: "assistant", text: "Done." }, - ]) - assert.deepEqual(events("models")[0], { selected: "p/m1", models: [{ id: "m1", provider_id: "p", name: "M1" }] }) - assert.deepEqual(events("status").at(-1), { state: "idle" }) - - // Streaming: this conversation's events only. - await service.push({ type: "session.text.delta", data: { sessionID: "ses_other", delta: "no" } }) - await service.push({ type: "session.execution.started", data: { sessionID: "ses_old" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "Hel" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "lo" } }) - await service.push({ - type: "permission.asked", - data: { sessionID: "ses_old", id: "per_1", action: "godot_execute_code" }, - }) - assert.deepEqual(events("assistant_delta"), [{ text: "Hel" }, { text: "lo" }]) - assert.deepEqual(events("status").at(-1), { state: "busy" }) - assert.deepEqual(events("permission"), [{ request_id: "per_1", action: "godot_execute_code", resources: [] }]) - - await call("permission_reply", { request_id: "per_1", reply: "once" }) - await call("prompt", { text: "Add a light" }) - await call("switch_model", { model: "p/m1" }) - await call("interrupt") - const names = service.calls.map(([name]) => name) - assert.deepEqual(service.calls.find(([name]) => name === "permission.reply")?.[1], { - sessionID: "ses_old", - requestID: "per_1", - decision: "once", - }) - assert.deepEqual(service.calls.find(([name]) => name === "session.prompt")?.[1], { - sessionID: "ses_old", - text: "Add a light", - }) - assert.ok(names.includes("session.switchModel") && names.includes("session.interrupt")) - assert.deepEqual(host, [ - ["resume", { script_handle: "godot:1:trial", session_id: "ses_old" }], - ["cancel", { script_handle: "godot:1:trial", session_id: "ses_old" }], - ]) - - // New: another conversation, marked for the same project, on the same offer; the previous one is released. - await call("new_session", CONNECT) - const created = service.calls.find(([name]) => name === "session.create")?.[1] - assert.deepEqual(created, { - title: "Godot: Trial", - location: { directory: CONNECT.directory }, - metadata: { [PROJECT_MARKER]: KEY }, - }) - assert.deepEqual(service.bindings, new Map([["ses_new1", "offer_trial"]])) - assert.deepEqual(events("session").at(-1), { - id: "ses_new1", - resumed: false, - model: "p/m1", - agent: null, - workspace: CONNECT.directory, - }) - - // Close: this conversation only; the offer is never withdrawn and never announced by the panel. - await call("close") - assert.deepEqual(service.bindings, new Map()) - assert.deepEqual(host.at(-1), ["cancel", { script_handle: "godot:1:trial", session_id: "ses_new1" }]) - await call("prompt", { text: "late" }) - assert.equal(events("error").at(-1)?.message, "Choose Connect first.") - const rpcMethods = new Set(service.calls.map(([name]) => name).filter((name) => name.startsWith("rpc."))) - assert.deepEqual(rpcMethods, new Set(["rpc.hosts", "rpc.attachHost", "rpc.bindingRead", "rpc.detachHost"])) - } finally { - await panel.closeAll() - } -}) - -it("Connect refuses an ambiguous or absent offer, keeps a conversation attached elsewhere and hides SDK errors", async () => { - const { service, panel, call, events } = harness() - try { - service.setOffers([ - { offerID: "offer_a", label: "Godot: Trial — main.tscn", protocol: "ok" }, - { offerID: "offer_b", label: "Godot: Trial — main.tscn", protocol: "ok" }, - ]) - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /^Several Godot editors offer Godot: Trial — main\.tscn/) - service.setOffers([]) - await call("connect", CONNECT) - assert.equal(events("error").at(-1)?.message, "This project is not offered to OpenCode yet; choose Connect again.") - assert.equal(service.calls.filter(([name]) => name === "rpc.attachHost").length, 0) - - // The marked conversation is attached to another application: never taken from it. - service.setOffers([ - { offerID: "offer_trial", label: "Godot: Trial — main.tscn", protocol: "ok" }, - { offerID: "offer_blender", label: "Blender: trial.blend", protocol: "ok" }, - ]) - service.bindings.set("ses_old", "offer_blender") - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /attached to another application/) - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - // Attached here, then moved elsewhere by another client: closing leaves that binding alone. - service.bindings.clear() - await call("connect", CONNECT) - service.bindings.set("ses_old", "offer_blender") - await call("close") - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - for (const bad of [{ token: "short" }, { host: "10.0.0.1" }, { offer_label: "" }]) { - await call("connect", { ...CONNECT, ...bad }) - assert.match( - String(events("error").at(-1)?.message), - /^The panel action failed: (Invalid host endpoint|Incomplete connect request)\. Check that OpenCode runs/, - ) - } - service.bindings.clear() - await call("connect", CONNECT) - ;(service.api.session as { prompt: unknown }).prompt = async () => { - throw new Error(`token ${HOST.token} on port ${HOST.port}`) - } - await call("prompt", { text: "x" }) - const message = events("error").at(-1)?.message as string - assert.ok(!message.includes(HOST.token) && !message.includes(String(HOST.port)), message) - } finally { - await panel.closeAll() - } -}) - -// Real trial: the first Connect failed while OpenCode opened the script's folder (its Location) and loaded its plugins -// ("RPC is unavailable"); it was read as the CodeNomad conversation attached to the same script holding it. -it("Connect waits for the Location OpenCode is still opening, next to a conversation attached to the same project", async () => { - const { service, panel, call, events } = harness(10_000) - try { - service.bindings.set("ses_codenomad", "offer_trial") - service.setUnavailable(2) - await call("connect", CONNECT) - assert.deepEqual(events("error"), []) - assert.equal(service.calls.filter(([name]) => name === "rpc.hosts").length, 3) - // Both conversations are attached to the project; closing the dock leaves the other one attached. - assert.deepEqual( - service.bindings, - new Map([ - ["ses_codenomad", "offer_trial"], - ["ses_old", "offer_trial"], - ]), - ) - await call("close") - assert.deepEqual(service.bindings, new Map([["ses_codenomad", "offer_trial"]])) - } finally { - await panel.closeAll() - } -}) - -it("a failed Connect says which step failed and why, without a credential", async () => { - const { service, panel, call, events } = harness(-1) - try { - service.setUnavailable(1) - await call("connect", CONNECT) - assert.equal( - events("error").at(-1)?.message, - "Connect failed while finding this project's offer: RPC is unavailable: neuralnomads.godot. Check that OpenCode runs, then choose Connect.", - ) - ;(service.api.session as { list: unknown }).list = async () => { - throw new Error(`refused by 127.0.0.1:${HOST.port} with Basic secret ${HOST.token}\nstack`) - } - await call("connect", CONNECT) - const message = String(events("error").at(-1)?.message) - assert.match( - message, - /^Connect failed while finding this project's conversation: refused by 127\.0\.0\.1:… with Basic …/, - ) - assert.ok( - !message.includes(HOST.token) && !message.includes(String(HOST.port)) && !message.includes("stack"), - message, - ) - } finally { - await panel.closeAll() - } -}) - -it("Connect without a running OpenCode says so", async () => { - const out: Out[] = [] - const panel = createPanel({ discover: async () => undefined, send: (message) => out.push(message as never) }) - await panel.dispatch({ id: "1", channel: "panel", method: "connect", params: CONNECT }) - assert.equal(out[0]?.data.message, "Start OpenCode before connecting the panel.") - assert.deepEqual(out[1], { id: "1", error: { message: "Panel action failed." } }) -}) diff --git a/integrations/houdini/host/scripts/opencode_houdini/__init__.py b/integrations/houdini/host/scripts/opencode_houdini/__init__.py index 4051ee0..98cb012 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/__init__.py +++ b/integrations/houdini/host/scripts/opencode_houdini/__init__.py @@ -118,6 +118,10 @@ def offerInfo() -> dict: return {"label": _host.label, "offer_key": OFFER_KEY, "advertising": _advertiser is not None} +def panelServices() -> list: + return _advertiser.results if _advertiser is not None else [] + + def scriptHandle(script=None) -> str: if _host is None: raise RuntimeError("OpenCode Houdini host has not been initialised") diff --git a/integrations/houdini/host/scripts/opencode_houdini/advertiser.py b/integrations/houdini/host/scripts/opencode_houdini/advertiser.py index 929d238..51045f3 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/advertiser.py +++ b/integrations/houdini/host/scripts/opencode_houdini/advertiser.py @@ -85,12 +85,13 @@ def _renew(self, offer: dict[str, Any]) -> list[dict[str, Any]]: if targets and self._count % DISCOVER_EVERY: results, kept = [], {} for name, (service, directory) in targets.items(): + body = None try: status, body = opencode_service.call(service, RPC_ID, "advertise", offer, directory, RENEW_TIMEOUT) outcome = opencode_service._outcome("advertise", status, body) except (OSError, ValueError): outcome = "error" - results.append({"service": name, "outcome": outcome}) + results.append({"service": name, "outcome": outcome, **opencode_service.panel_runtime(outcome, body)}) if outcome in ("accepted", "renewed"): kept[name] = (service, directory) self._targets = kept @@ -104,6 +105,7 @@ def _renew(self, offer: dict[str, Any]) -> list[dict[str, Any]]: services = [] for service in services: outcome = "unavailable" + body = None for directory in opencode_service.location_candidates(None, self._env): try: deadline = time.monotonic() + RENEW_TIMEOUT @@ -121,7 +123,7 @@ def _renew(self, offer: dict[str, Any]) -> list[dict[str, Any]]: if outcome in ("accepted", "renewed"): found[service.file] = (service, directory) break - results.append({"service": service.file, "outcome": outcome}) + results.append({"service": service.file, "outcome": outcome, **opencode_service.panel_runtime(outcome, body)}) self._targets = found return results diff --git a/integrations/houdini/host/scripts/opencode_houdini/panel.py b/integrations/houdini/host/scripts/opencode_houdini/panel.py index 60f5478..82c5cd4 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/panel.py +++ b/integrations/houdini/host/scripts/opencode_houdini/panel.py @@ -3,7 +3,6 @@ import json import os from pathlib import Path -import shutil import uuid import hou @@ -12,6 +11,12 @@ import opencode_houdini +def panel_launcher(results, override): + from .opencode_service import panel_launcher as choose + + return choose(results, override) + + def _log(message: str) -> None: pass # Conversation data and host credentials stay in memory. @@ -37,29 +42,63 @@ def __init__(self, parent=None) -> None: self._process.errorOccurred.connect(self._process_error) self._process.finished.connect(self._finished) self._stdout = b"" - self._pending: list[bytes] = [] + self._pending: list[tuple] = [] + self._targets: dict[str, dict] = {} + self._problem = "" self._request = 0 + self._timer = QtCore.QTimer(self) + self._timer.timeout.connect(self.start) + self._timer.start(1000) def start(self) -> None: - if self._process.state() != QtCore.QProcess.ProcessState.NotRunning: + if not self._targets or self._process.state() != QtCore.QProcess.ProcessState.NotRunning: return - node = os.environ.get("NEURALNOMADS_HOUDINI_NODE") or shutil.which("node") + services = opencode_houdini.panelServices() + runtime, bun = panel_launcher(services, "NEURALNOMADS_HOUDINI_NODE") sidecar = str(Path(__file__).resolve().parents[2] / "sidecar.cjs") - if not node: - self.diagnostic.emit("Install Node.js 22 or set NEURALNOMADS_HOUDINI_NODE") - return + problem = "" if not Path(sidecar).is_file(): - _log("sidecar missing: " + sidecar) - self.diagnostic.emit( - "OpenCode Link sidecar is missing; reinstall the application part." - ) + problem = "OpenCode Link sidecar is missing; reinstall the application part." + elif not runtime and services: + problem = "No OpenCode runtime, NEURALNOMADS_HOUDINI_NODE executable, or Node on PATH." + if problem and problem != self._problem: + self.diagnostic.emit(problem) + self._problem = problem + if problem or not runtime: return - self._process.setProgram(node) + env = QtCore.QProcessEnvironment.systemEnvironment() + env.remove("BUN_BE_BUN") + if bun: + env.insert("BUN_BE_BUN", "1") + self._process.setProcessEnvironment(env) + self._process.setProgram(runtime) self._process.setArguments([sidecar]) self._process.setWorkingDirectory(str(Path(sidecar).resolve().parent.parent)) self._process.start() def send(self, channel: str, method: str, params: dict) -> None: + if method in ("connect", "new_session"): + previous = self._targets.get(channel, {}) + if method == "new_session" or previous.get("directory") != params.get("directory"): + self._pending = [item for item in self._pending if item[0] != channel] + else: + params = {**params, "session_id": previous.get("session_id"), "draft": previous.get("draft", False)} + self._targets[channel] = params + elif method == "close": + self._targets.pop(channel, None) + self._pending = [item for item in self._pending if item[0] != channel] + if self._process.state() == QtCore.QProcess.ProcessState.Running: + self._write(channel, method, params) + elif method not in ("connect", "new_session", "close"): + if method == "interrupt": + self._pending = [item for item in self._pending if item[0] != channel or item[1] != "prompt"] + if len(self._pending) >= 100: + self.diagnostic.emit("OpenCode sidecar request queue is full") + return + self._pending.append((channel, method, params)) + self.start() + + def _write(self, channel, method, params): self._request += 1 _log("send method=" + method + " channel=" + channel + " params=" + json.dumps({key: value for key, value in params.items() if key != "token"}, default=str)) message = ( @@ -69,13 +108,7 @@ def send(self, channel: str, method: str, params: dict) -> None: ) + "\n" ).encode("utf-8") - if self._process.state() == QtCore.QProcess.ProcessState.Running: - self._process.write(message) - elif len(self._pending) < 100: - self._pending.append(message) - self.start() - else: - self.diagnostic.emit("OpenCode sidecar request queue is full") + self._process.write(message) def stop(self) -> None: if self._process.state() != QtCore.QProcess.ProcessState.NotRunning: @@ -85,8 +118,11 @@ def stop(self) -> None: def _started(self) -> None: _log("sidecar started") pending, self._pending = self._pending, [] - for message in pending: - self._process.write(message) + self._problem = "" + for channel, params in self._targets.items(): + self._write(channel, "connect", params) + for item in pending: + self._write(*item) def _read_stdout(self) -> None: self._stdout += bytes(self._process.readAllStandardOutput()) @@ -98,12 +134,15 @@ def _read_stdout(self) -> None: message = json.loads(raw.decode("utf-8")) _log("recv " + json.dumps(message, default=str)[:2000]) if message.get("event"): + channel = str(message.get("channel", "")) + if message["event"] == "session" and channel in self._targets: + self._targets[channel] = {**self._targets[channel], "session_id": message["data"]["id"], "draft": message["data"].get("draft", False)} self.eventReceived.emit( - str(message.get("channel", "")), + channel, str(message["event"]), message.get("data") or {}, ) - elif message.get("error"): + elif message.get("error") and not message.get("id"): self.diagnostic.emit(str(message["error"].get("message", message["error"]))) except Exception: self.diagnostic.emit("Malformed sidecar output: " + raw[:200].decode("utf-8", "replace")) @@ -120,7 +159,9 @@ def _process_error(self, error) -> None: def _finished(self, exit_code, exit_status) -> None: _log("sidecar finished exit=" + str(exit_code) + " status=" + str(exit_status)) - self.diagnostic.emit("OpenCode sidecar stopped with exit code " + str(exit_code)) + self._stdout = b"" + for channel in self._targets: + self.eventReceived.emit(channel, "status", {"state": "connecting"}) class PromptEdit(QtWidgets.QPlainTextEdit): @@ -134,6 +175,14 @@ def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: super().keyPressEvent(event) +class Conversations(QtWidgets.QComboBox): + opening = QtCore.Signal() + + def showPopup(self) -> None: + self.opening.emit() + super().showPopup() + + class OpenCodePanel(QtWidgets.QWidget): def __init__(self, parent=None) -> None: super().__init__(parent) @@ -150,7 +199,12 @@ def __init__(self, parent=None) -> None: self._client.diagnostic.connect(self._diagnostic) self.destroyed.connect(self._destroyed) hou.hipFile.addEventCallback(self._hip_event) - self._status.setText("DISCONNECTED") + opencode_houdini.acquirePanel(self._channel) + self._target = None + self._sync() + self._timer = QtCore.QTimer(self) + self._timer.timeout.connect(self._sync) + self._timer.start(500) def _build_ui(self) -> None: layout = QtWidgets.QVBoxLayout(self) @@ -162,16 +216,13 @@ def _build_ui(self) -> None: self._session = QtWidgets.QLabel("SESSION connecting") self._status = QtWidgets.QLabel("STARTING") self._status.setObjectName("openCodeHoudiniStatus") - self._new = QtWidgets.QPushButton("New") - self._connect_button = QtWidgets.QPushButton("Connect") - self._disconnect_button = QtWidgets.QPushButton("Disconnect") + self._conversations = Conversations() + self._conversations.addItem("New conversation", None) header.addWidget(brand) header.addWidget(self._session) header.addStretch(1) header.addWidget(self._status) - header.addWidget(self._new) - header.addWidget(self._connect_button) - header.addWidget(self._disconnect_button) + header.addWidget(self._conversations) layout.addLayout(header) self._transcript = QtWidgets.QTextEdit() @@ -200,8 +251,6 @@ def _build_ui(self) -> None: self._stop = QtWidgets.QPushButton("Stop") self._send = QtWidgets.QPushButton("Send") self._stop.setEnabled(False) - self._send.setEnabled(False) - self._prompt.setEnabled(False) prompt_row.addWidget(self._prompt, 1) prompt_row.addWidget(self._stop) prompt_row.addWidget(self._send) @@ -213,9 +262,8 @@ def _build_ui(self) -> None: "#openCodeHoudiniStatus { color: #d5a657; font-weight: 600; }" "#openCodeHoudiniTranscript { border: 1px solid #34393e; background: #191b1d; }" ) - self._new.clicked.connect(self._new_session) - self._connect_button.clicked.connect(self._connect) - self._disconnect_button.clicked.connect(self._disconnect) + self._conversations.activated.connect(self._choose_conversation) + self._conversations.opening.connect(lambda: self._client.send(self._channel, "list", {})) self._send.clicked.connect(self._send_prompt) self._prompt.sendRequested.connect(self._send_prompt) self._stop.clicked.connect(lambda: self._client.send(self._channel, "interrupt", {})) @@ -230,41 +278,30 @@ def _connect_params(self) -> dict: offer = opencode_houdini.offerInfo() return { **info, - # This Houdini offers itself (OpenCode Link starts with Houdini): the panel finds that offer by its - # label and attaches its own conversation to it, which it takes back per file next time. "offer_label": offer["label"], - "sessions_file": str(Path(__file__).resolve().parents[3].parent / "panel-sessions.json"), "script_handle": opencode_houdini.scriptHandle(), - "script_key": "untitled:" + opencode_houdini.scriptHandle() if is_untitled else str(Path(file_name).resolve()), - "script_name": hou.hipFile.basename(), "directory": directory, } - def _connect(self) -> None: + def _sync(self) -> None: if self._disposed: return - opencode_houdini.acquirePanel(self._channel) - self._connected = False - self._status.setText("CONNECTING") - self._send.setEnabled(False) - self._prompt.setEnabled(False) - self._client.send(self._channel, "connect", self._connect_params()) + params = self._connect_params() + if params != self._target: + self._target = params + self._client.send(self._channel, "connect", params) def _new_session(self) -> None: if self._disposed: return - opencode_houdini.acquirePanel(self._channel) - self._status.setText("CONNECTING") - self._client.send(self._channel, "new_session", self._connect_params()) + self._client.send(self._channel, "new_session", self._target) - def _disconnect(self) -> None: - # The host and its offer stay: other conversations attached to this Houdini keep it. - opencode_houdini.releasePanel(self._channel) - self._client.send(self._channel, "close", {}) - self._connected = False - self._send.setEnabled(False) - self._prompt.setEnabled(False) - self._status.setText("DISCONNECTED") + def _choose_conversation(self, index: int) -> None: + session = self._conversations.itemData(index) + if session: + self._client.send(self._channel, "open", {"session_id": session}) + else: + self._new_session() def _send_prompt(self) -> None: if self._busy: @@ -273,7 +310,6 @@ def _send_prompt(self) -> None: if not text: return self._prompt.clear() - self._append("user", text) self._client.send(self._channel, "prompt", {"text": text}) def _permission_reply(self, reply: str) -> None: @@ -293,12 +329,22 @@ def _event(self, channel: str, name: str, data: dict) -> None: return if name == "session": self._connected = True - self._session.setText("SESSION " + str(data.get("id", ""))[-8:]) + self._session.setText("SESSION " + str(data["id"])[-8:] if data.get("id") else "New conversation") self._append("system", "Resumed session" if data.get("resumed") else "New session") elif name == "history": self._transcript.clear() for message in data.get("messages", []): self._append(message.get("role", "system"), message.get("text", "")) + elif name == "conversations": + self._conversations.clear() + self._conversations.addItem("New conversation", None) + for entry in data["entries"]: + self._conversations.addItem(entry.get("title") or "Untitled", entry["id"]) + self._conversations.setCurrentIndex(max(0, self._conversations.findData(data.get("selected")))) + elif name == "notice": + self._append("system", data["message"]) + elif name == "user_message": + self._append("user", data["text"]) elif name == "assistant_start": self._start_assistant() elif name == "assistant_delta": @@ -316,10 +362,14 @@ def _event(self, channel: str, name: str, data: dict) -> None: elif name == "status": state = str(data.get("state", "unknown")) self._status.setText(state.upper()) + if state == "connecting": + self._connected = False + self._permission_request = None + self._permission.hide() self._busy = state in ("busy", "retry") - self._stop.setEnabled(self._busy) - self._send.setEnabled(self._connected and not self._busy) - self._prompt.setEnabled(self._connected and not self._busy) + self._stop.setEnabled(self._busy or state == "connecting") + self._send.setEnabled(not self._busy) + self._prompt.setEnabled(not self._busy) elif name == "graph_revision": self._status.setToolTip("Houdini graph revision " + str(data.get("revision"))) elif name == "error": @@ -327,8 +377,8 @@ def _event(self, channel: str, name: str, data: dict) -> None: self._status.setText("ERROR") self._busy = False self._stop.setEnabled(False) - self._send.setEnabled(self._connected) - self._prompt.setEnabled(self._connected) + self._send.setEnabled(True) + self._prompt.setEnabled(True) @QtCore.Slot(str) def _diagnostic(self, text: str) -> None: @@ -380,7 +430,7 @@ def _hip_event(self, event_type: hou.hipFileEventType) -> None: hou.hipFileEventType.AfterClear, hou.hipFileEventType.AfterLoad, ): - self._disconnect() + self._sync() def dispose(self) -> None: if self._disposed: diff --git a/integrations/houdini/plugin/README.md b/integrations/houdini/plugin/README.md index 0e8785a..77ae0ad 100644 --- a/integrations/houdini/plugin/README.md +++ b/integrations/houdini/plugin/README.md @@ -1,6 +1,6 @@ # OpenCode for Houdini (preview) -Read, change and check the scene open in Houdini from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode Link** panel inside Houdini. Houdini 21 or later and OpenCode 2.2 or later are required; the panel also needs Node.js 22 or later. +Read, change and check the scene open in Houdini from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode Link** panel inside Houdini. Houdini 21 or later and OpenCode 2.2 or later are required. ## Install @@ -41,7 +41,7 @@ A call that outlasts its wait says whether Houdini still runs it (OpenCode Link ## The OpenCode Link panel -The **OpenCode Link** Python panel is a conversation inside Houdini. **Connect** attaches the panel's conversation to this Houdini's own offer, taking back the conversation it had for this file; **New** starts another. Closing the panel releases its conversation only: Houdini stays offered and other conversations attached to it keep it. The panel and other conversations (CodeNomad's, for instance) can be attached to the same Houdini together; both write to the same scene, each change checked against its revision. The panel's conversation lives in its project folder: the first Connect there waits while OpenCode opens that folder and loads its plugins. A failed Connect says which step failed and why. Node.js is found on `PATH`; `NEURALNOMADS_HOUDINI_NODE` names another one. +The **OpenCode Link** Python panel connects automatically to the latest conversation in the HIP file’s folder. Opening another version in that folder keeps the selected conversation. Use the selector to switch or choose **New conversation**; nothing is created until you send a message. **Stop** interrupts or clears queued prompts. The panel uses OpenCode’s executable, with Node.js 22+ (`NEURALNOMADS_HOUDINI_NODE` or `PATH`) as a fallback. ## Limits diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip index ce75f9ef5e101fb1f955450049e664c33ef37367..b8d211f8e6e35018f53f87ac3671b77447802395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{j1g-@!mk$`l?kmdE$d_9(nVFP#^j?IMDfy3VGkF)|CGD5A2Kb{|f@F BUIPFC diff --git a/integrations/houdini/plugin/package.json b/integrations/houdini/plugin/package.json index 7b4312f..b82a34c 100644 --- a/integrations/houdini/plugin/package.json +++ b/integrations/houdini/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.3.1", "appVersions": ">=21.0", "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "7efd8d521a82d7e409251ae89ad6390bfcf99cb85af72b64aa5ead05321a7aa0" + "sha256": "17fb6556f0e4166341aef655a5c475f46b9844e7e7f1e68112d00ab900ce94c6" } } } diff --git a/integrations/houdini/plugin/src/sidecar-steps.ts b/integrations/houdini/plugin/src/sidecar-steps.ts deleted file mode 100644 index 2fed858..0000000 --- a/integrations/houdini/plugin/src/sidecar-steps.ts +++ /dev/null @@ -1,65 +0,0 @@ -// The panel's Connect steps that do not need OpenCode's client (sidecar.ts): finding this Houdini's offer while the -// service opens the panel's Location, and an error that says which step failed, safe to show in the panel. - -// A message of the sidecar's own, safe to show in the panel. -export class PanelError extends Error {} - -// How long Connect waits for this Houdini's own offer (it offers itself every 5 s from its start), and for a -// Location OpenCode opens for the panel to load its plugins (tens of seconds in a trial). -export const OFFER_WAIT_MS = 30_000 - -// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. -export function briefly(error: unknown) { - const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") - .split(/\r?\n/)[0] - ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") - .replace(/(basic|bearer)\s+\S+/gi, "$1 …") - .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") - .slice(0, 240) - return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` -} - -// A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. -export async function step(doing: string, work: () => Promise): Promise { - try { - return await work() - } catch (error) { - if (error instanceof PanelError) throw error - throw new PanelError( - `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - ) - } -} - -type Offer = { label: string; offerID: string } - -// This Houdini's offer: the one with its label among the offered hosts (Houdini offers itself; the panel never). -export async function findOffer( - hosts: () => Promise<{ offers?: unknown } | undefined>, - label: string, - wait = { ms: OFFER_WAIT_MS, sleep: (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) }, -): Promise { - const until = Date.now() + wait.ms - for (;;) { - let result: { offers?: unknown } | undefined - try { - result = await hosts() - } catch (error) { - // The first call in the panel's folder: OpenCode opens that Location and loads its plugins meanwhile, and the - // integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). - if (!/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || Date.now() > until) - throw error - await wait.sleep(1_000) - continue - } - const offers = ((result?.offers ?? []) as Offer[]).filter((offer) => offer.label === label) - if (offers.length > 1) - throw new PanelError(`Several Houdinis offer ${label}: attach this conversation from OpenCode (houdini_hosts).`) - if (offers[0]) return offers[0] - if (Date.now() > until) - throw new PanelError( - "This Houdini does not offer itself to OpenCode (OPENCODE_HOUDINI_OFFER=0, or OpenCode Link not started).", - ) - await wait.sleep(1_000) - } -} diff --git a/integrations/houdini/plugin/src/sidecar.ts b/integrations/houdini/plugin/src/sidecar.ts index 2ebc8b6..c1ffa0b 100644 --- a/integrations/houdini/plugin/src/sidecar.ts +++ b/integrations/houdini/plugin/src/sidecar.ts @@ -1,260 +1,3 @@ -// Private JSONL panel client. Built into the installed host; credentials never leave this process. -import { mkdirSync, readFileSync, writeFileSync } from "node:fs" -import { dirname } from "node:path" -import readline from "node:readline" -import { OpenCode } from "@opencode/client" -import { Service } from "@opencode/client/service" -import { rpcDefinition } from "../../../../packages/integration-kit/src/contract.ts" -import { requestHost } from "../../../../packages/integration-kit/src/host-client.ts" -import { briefly, findOffer, PanelError, step } from "./sidecar-steps.ts" +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" -type Channel = { - id: string - directory: string - sessionID: string - label: string - binding: { host: string; port: number; token: string } - handle: string - abort: AbortController - timer?: NodeJS.Timeout - pending: boolean -} -type Request = { id: string; channel: string; method: string; params: Record } -type Rpc = Record Promise>> -let client: ReturnType | undefined -let rpc: Rpc -const channels = new Map() -const queues = new Map>() -const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) -const event = (c: Channel, name: string, data: object) => send({ channel: c.id, event: name, data }) -const options = (c: { directory: string }) => ({ - location: { directory: c.directory }, - signal: AbortSignal.timeout(3000), -}) -async function api() { - if (client) return client - const endpoint = await Service.discover() - if (!endpoint) throw new PanelError("Start OpenCode before connecting the panel.") - client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) - rpc = client.rpc(rpcDefinition("neuralnomads.houdini", "native") as never) as unknown as Rpc - return client -} - -// The panel's conversation per Houdini file, kept next to the installed payloads: Connect takes it back. -type Sessions = Record -function readSessions(file: string): Sessions { - try { - const value = JSON.parse(readFileSync(file, "utf8")) as unknown - return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Sessions) : {} - } catch { - return {} - } -} -function rememberSession(file: string, key: string, session: string, directory: string) { - if (!file || !key || key.startsWith("untitled:")) return - try { - const sessions = readSessions(file) - sessions[key] = { session, directory } - const keys = Object.keys(sessions) - for (const old of keys.slice(0, Math.max(0, keys.length - 200))) delete sessions[old] - mkdirSync(dirname(file), { recursive: true }) - writeFileSync(file, `${JSON.stringify(sessions)}\n`) - } catch { - // a conversation that is not taken back next time - } -} - -async function attached(c: Channel) { - const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) - return read?.state === "attached" && (read.binding as { label?: string } | undefined)?.label === c.label -} - -// Closing the panel releases its own conversation only: the offer stays, and other conversations attached to -// this Houdini (CodeNomad, a terminal) keep it. -async function close(c: Channel) { - channels.delete(c.id) - if (c.timer) clearInterval(c.timer) - c.abort.abort() - await requestHost( - c.binding, - "cancel", - { script_handle: c.handle, session_id: c.sessionID }, - { timeoutMs: 2000 }, - ).catch(() => {}) - // A different client may have moved the session to another host. Never detach that binding. - await attached(c) - .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) - .catch(() => {}) -} - -async function stream(c: Channel) { - const service = await api() - try { - for await (const item of service.event.subscribe({ signal: c.abort.signal })) { - const data = item.data as unknown as Record - if (data.sessionID !== c.sessionID) continue - if (item.type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) - else if (item.type === "session.text.ended") event(c, "assistant_end", {}) - else if (item.type === "session.execution.started") event(c, "status", { state: "busy" }) - else if (item.type === "session.execution.succeeded" || item.type === "session.execution.interrupted") - event(c, "status", { state: "idle" }) - else if (item.type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) - else if (item.type === "permission.asked") - event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources }) - } - } catch { - if (!c.abort.signal.aborted) event(c, "error", { message: "OpenCode disconnected; choose Connect to reconnect." }) - } -} - -async function connect(id: string, params: Record, fresh: boolean) { - const service = await step("reaching OpenCode", api) - const previous = channels.get(id) - if (previous) await close(previous) - if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) - throw new Error("Invalid host endpoint.") - const directory = String(params.directory ?? "") - if (!directory) throw new Error("Select a project directory.") - const label = String(params.offer_label ?? "") - if (!label) throw new PanelError("This Houdini's offer is unknown.") - const key = String(params.script_key ?? "") - const store = String(params.sessions_file ?? "") - // The file's conversation, when it still exists; otherwise (or with New) a new one. - let sessionID: string | undefined - let resumed = false - const known = !fresh && store ? readSessions(store)[key] : undefined - if (known?.session) { - try { - const found = (await service.session.get({ sessionID: known.session } as never)) as { id?: string } | undefined - if (found?.id === known.session) { - sessionID = known.session - resumed = true - } - } catch { - // gone: a new one - } - } - if (!sessionID) { - const label = String(params.script_name || "Houdini") - sessionID = ( - await step("creating this file's conversation", () => - service.session.create({ title: `Houdini: ${label}`, location: { directory } }), - ) - ).id - } - const c: Channel = { - id, - directory: resumed && known ? known.directory : directory, - sessionID, - label, - binding: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, - handle: String(params.script_handle), - abort: new AbortController(), - pending: false, - } - try { - const offer = await step("finding this Houdini's offer", () => - findOffer(async () => rpc.hosts?.({}, options(c)), c.label), - ) - const result = await step("attaching the conversation to this Houdini", async () => - rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), - ) - if (result?.outcome !== "attached") throw new PanelError("Houdini attachment was refused.") - rememberSession(store, key, c.sessionID, c.directory) - channels.set(id, c) - let warned = false - c.timer = setInterval(() => { - if (c.pending) return - c.pending = true - void api() - .then(() => attached(c)) - .then((still) => { - if (!still) throw new Error("detached") - }) - .catch(() => { - client = undefined - if (!warned) - event(c, "error", { message: "Conversation detached or service unavailable; choose Connect to reconnect." }) - warned = true - }) - .finally(() => { - c.pending = false - }) - }, 5000) - void stream(c) - event(c, "session", { id: c.sessionID, resumed }) - event(c, "history", { messages: [] }) - event(c, "status", { state: "idle" }) - } catch (error) { - await close(c) - throw error - } -} -async function dispatch(request: Request) { - try { - const params = request.params ?? {} - if (request.method === "connect" || request.method === "new_session") - await connect(request.channel, params, request.method === "new_session") - else { - const c = channels.get(request.channel) - if (!c) throw new Error("Choose Connect first.") - const service = await api() - if (request.method === "close") await close(c) - else if (request.method === "interrupt") { - await requestHost( - c.binding, - "cancel", - { script_handle: c.handle, session_id: c.sessionID }, - { timeoutMs: 2000 }, - ) - await service.session.interrupt({ sessionID: c.sessionID, resume: false }) - } else if (request.method === "prompt") { - if (!(await attached(c))) throw new PanelError("Houdini was detached; choose Connect to attach again.") - await requestHost( - c.binding, - "resume", - { script_handle: c.handle, session_id: c.sessionID }, - { timeoutMs: 2000 }, - ) - await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) - } else if (request.method === "permission_reply") { - const decision = params.reply - if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") - await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) - } else throw new Error("Unknown panel action.") - } - send({ id: request.id, result: {} }) - } catch (error) { - // SDK and host errors in one line, without credentials or endpoints (briefly). - send({ - channel: request.channel, - event: "error", - data: { - message: - error instanceof PanelError - ? error.message - : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - }, - }) - send({ id: request.id, error: { message: "Panel action failed." } }) - } -} - -const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) -input.on("line", (line) => { - try { - if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") - const request = JSON.parse(line) as Request - if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") - const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => dispatch(request)) - queues.set(request.channel, next) - void next.finally(() => { - if (queues.get(request.channel) === next) queues.delete(request.channel) - }) - } catch { - send({ error: { message: "Invalid panel request." } }) - } -}) -input.on("close", () => { - void Promise.allSettled([...channels.values()].map(close)).finally(() => process.exit(0)) -}) +runPanel({ app: "Houdini", rpcID: "neuralnomads.houdini", document: "file", duplicateOffer: "Houdini instances" }) diff --git a/integrations/houdini/test/host_probe.py b/integrations/houdini/test/host_probe.py index 3243a54..838cc18 100644 --- a/integrations/houdini/test/host_probe.py +++ b/integrations/houdini/test/host_probe.py @@ -341,6 +341,7 @@ def test_renewals_go_straight_to_the_service_and_discover_again_after_a_failure( fake._ready = lambda service, rpc, directory, deadline: (calls.append("status") or (200, {"output": {}})) fake._unavailable = lambda status, body: False fake._outcome = lambda method, status, body: body + fake.panel_runtime = lambda outcome, body: {} fake.call = lambda service, rpc, method, payload, directory, timeout: ( calls.append("%s:%.0f" % (method, timeout)) or (200, outcomes.pop(0) if outcomes else "renewed")) sys.modules["opencode_houdini.opencode_service"] = fake diff --git a/integrations/houdini/test/panel_probe.py b/integrations/houdini/test/panel_probe.py index 1eb6d40..7061c98 100644 --- a/integrations/houdini/test/panel_probe.py +++ b/integrations/houdini/test/panel_probe.py @@ -32,7 +32,7 @@ class Widget: def closeEvent(self, event): event.accept() -qt.QtWidgets = types.SimpleNamespace(QWidget=Widget, QPlainTextEdit=object) +qt.QtWidgets = types.SimpleNamespace(QWidget=Widget, QPlainTextEdit=object, QComboBox=object) sys.modules["PySide6"] = qt @@ -72,10 +72,14 @@ def test_installed_import(self): process.state.return_value = 0 client = panel.JsonlClient.__new__(panel.JsonlClient) client._process = process - with patch.object(panel.shutil, "which", return_value=sys.executable): + client._targets = {"test": {}} + client._problem = "" + qt.QtCore.QProcessEnvironment = Mock() + with patch.object(panel, "panel_launcher", return_value=(sys.executable, True)): client.start() process.setArguments.assert_called_once_with([str(root / "sidecar.cjs")]) process.start.assert_called_once() + qt.QtCore.QProcessEnvironment.systemEnvironment.return_value.insert.assert_called_once_with("BUN_BE_BUN", "1") self.assertTrue((root / "sidecar.cjs").is_file()) def test_shared_host_lifetime(self): @@ -102,10 +106,12 @@ def test_shared_host_lifetime(self): widget._prompt = Mock() widget._session = Mock() widget._append = Mock() + widget._target = None + integration.acquirePanel(widget._channel) with patch.object(panel, "create_interface", return_value=widget): interfaces[index]["create_interface"] = panel.create_interface self.assertIs(interfaces[index]["onCreateInterface"](), widget) - widget._connect() + widget._sync() widget._event(widget._channel, "session", {"id": "session-" + str(index)}) endpoint = integration.hostInfo() host, server = integration._host, integration._server @@ -133,11 +139,6 @@ def ask(): self.assertEqual(result["result"]["script_handle"], state.handle) try: - first._disconnect() - client.send.assert_called_with(first._channel, "close", {}) - self.assertFalse(first._connected) - assert_live() - first._connect() first._new_session() interfaces[0]["onDestroyInterface"]() client.send.assert_called_with(first._channel, "close", {}) @@ -145,7 +146,7 @@ def ask(): sends = client.send.call_count interfaces[0]["onDestroyInterface"]() first._destroyed() - first._connect() + first._sync() self.assertEqual(client.send.call_count, sends) assert_live() # The last panel closing leaves the host with Houdini: its offer serves the other conversations. diff --git a/integrations/houdini/test/sidecar-steps.test.ts b/integrations/houdini/test/sidecar-steps.test.ts deleted file mode 100644 index 1423538..0000000 --- a/integrations/houdini/test/sidecar-steps.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -// The panel's Connect (sidecar.ts): its first call in a folder OpenCode is still opening waits for that Location's -// plugins ("RPC is unavailable"), and a failed Connect says which step failed and why, without a credential. Gaffer -// trial: the first Connect failed with "Connection or action failed" next to a CodeNomad conversation attached to -// the same application, and was read as that conversation holding it. - -import assert from "node:assert/strict" -import { it } from "node:test" - -import { briefly, findOffer, PanelError, step } from "../plugin/src/sidecar-steps.ts" - -const TOKEN = "a".repeat(64) -const offers = { offers: [{ offerID: "offer_shot", label: "Houdini: shot.hipnc" }] } - -it("Connect waits while OpenCode opens the panel's folder, then finds this Houdini's offer", async () => { - let calls = 0 - const slept: number[] = [] - const offer = await findOffer( - async () => { - calls += 1 - if (calls <= 2) throw new Error("RPC is unavailable: neuralnomads.houdini") - return offers - }, - "Houdini: shot.hipnc", - { ms: 30_000, sleep: async (ms) => void slept.push(ms) }, - ) - assert.equal(offer.offerID, "offer_shot") - assert.equal(calls, 3) - assert.deepEqual(slept, [1_000, 1_000]) -}) - -it("another error, or an RPC still unavailable at the deadline, ends the search", async () => { - await assert.rejects( - findOffer(async () => Promise.reject(new Error("socket hang up")), "Houdini: shot.hipnc", { - ms: 30_000, - sleep: async () => {}, - }), - /socket hang up/, - ) - await assert.rejects( - findOffer( - async () => Promise.reject(new Error("RPC is unavailable: neuralnomads.houdini")), - "Houdini: shot.hipnc", - { - ms: -1, - sleep: async () => {}, - }, - ), - /RPC is unavailable/, - ) - await assert.rejects( - findOffer(async () => ({ offers: [...offers.offers, ...offers.offers] }), "Houdini: shot.hipnc", { - ms: -1, - sleep: async () => {}, - }), - (error: Error) => error instanceof PanelError && /^Several Houdinis offer Houdini: shot\.hipnc/.test(error.message), - ) -}) - -it("a failed Connect says which step failed and why, without a credential", async () => { - await assert.rejects( - step("finding this Houdini's offer", async () => { - throw new Error("RPC is unavailable: neuralnomads.houdini") - }), - (error: Error) => - error instanceof PanelError && - error.message === - "Connect failed while finding this Houdini's offer: RPC is unavailable: neuralnomads.houdini. Check that OpenCode runs, then choose Connect.", - ) - await assert.rejects( - step("creating this file's conversation", async () => { - throw new Error(`refused by 127.0.0.1:4096 with Basic ${TOKEN} on port 51396\n at stack`) - }), - (error: Error) => { - assert.equal( - error.message, - "Connect failed while creating this file's conversation: refused by 127.0.0.1:… with Basic … on port …. Check that OpenCode runs, then choose Connect.", - ) - return true - }, - ) - // The panel's own messages pass as they are. - await assert.rejects( - step("reaching OpenCode", async () => { - throw new PanelError("Start OpenCode before connecting the panel.") - }), - (error: Error) => error instanceof PanelError && error.message === "Start OpenCode before connecting the panel.", - ) - assert.equal(briefly(new Error(`token ${TOKEN}`)), "token ….") -}) diff --git a/packages/integration-kit/python/opencode_service.py b/packages/integration-kit/python/opencode_service.py index 5354867..25451a0 100644 --- a/packages/integration-kit/python/opencode_service.py +++ b/packages/integration-kit/python/opencode_service.py @@ -29,6 +29,7 @@ import http.client import json import os +import shutil import re import time import urllib.error @@ -194,6 +195,14 @@ def _outcome(method, status, body): return value if status == 200 and value in OUTCOMES[method] else "error" +def panel_runtime(outcome, body): + if outcome in ("accepted", "renewed") and isinstance(body, dict): + runtime = body.get("output", {}).get("panel_runtime") + if isinstance(runtime, str) and os.path.isabs(runtime): + return {"panel_runtime": runtime} + return {} + + def _ready(service, rpc_id, directory, deadline): # Registration is asynchronous on cold Locations. Only the payload-free # status read is repeated; an advertisement/withdrawal is never a probe. @@ -213,6 +222,7 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env results = [] for service in discover(service_name, env, timeout): outcome = "unavailable" + runtime = {} for directory in location_candidates(config_dir_setting, env): try: deadline = time.monotonic() + timeout @@ -233,11 +243,25 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env outcome = "unavailable" else: outcome = _outcome(method, status, body) + if method == "advertise": + runtime = panel_runtime(outcome, body) break - results.append({"service": service.file, "outcome": outcome}) + results.append({"service": service.file, "outcome": outcome, **runtime}) return results +def panel_launcher(results, override): + """Use the daemon's advertised executable, then the host override, then Node on PATH.""" + for result in results: + runtime = result.get("panel_runtime") + if result.get("outcome") in ("accepted", "renewed") and isinstance(runtime, str) and os.path.isabs(runtime) and shutil.which(runtime): + return runtime, True + for candidate in (os.environ.get(override), "node"): + if candidate and (node := shutil.which(candidate)): + return node, False + return None, False + + def advertise_all(rpc_id, offer, service_name=None, config_dir_setting=None, env=None, timeout=TIMEOUT): """Advertise one offer to every discovered service, or to the named one.""" return _each_service("advertise", rpc_id, offer, service_name, config_dir_setting, env, timeout) diff --git a/packages/integration-kit/src/contract.ts b/packages/integration-kit/src/contract.ts index 0ebb211..f4422cd 100644 --- a/packages/integration-kit/src/contract.ts +++ b/packages/integration-kit/src/contract.ts @@ -203,9 +203,16 @@ export const RPC_SCHEMAS = { properties: { offerID: { type: "string", pattern: OFFER_ID_PATTERN }, sessionID: { type: "string", pattern: SESSION_ID_PATTERN }, + takeover: { type: "boolean" }, + }, + }, + "attachHost.output": { + ...outcome(["attached", "busy", "gone", "refused"]), + properties: { + outcome: { enum: ["attached", "busy", "gone", "refused"] }, + replaced: { type: "boolean" }, }, }, - "attachHost.output": outcome(["attached", "busy", "gone", "refused"]), "detachHost.input": { type: "object", additionalProperties: false, @@ -242,7 +249,13 @@ export const RPC_SCHEMAS = { }, ], }, - "advertise.output": outcome(["accepted", "renewed", "refused"]), + "advertise.output": { + ...outcome(["accepted", "renewed", "refused"]), + properties: { + outcome: { enum: ["accepted", "renewed", "refused"] }, + panel_runtime: { type: "string", maxLength: 4096 }, + }, + }, "withdraw.output": outcome(["withdrawn", "none"]), "status_changed.event": empty(), "hosts_changed.event": empty(), diff --git a/packages/integration-kit/src/integration-rpc.ts b/packages/integration-kit/src/integration-rpc.ts index 193868f..bcaebee 100644 --- a/packages/integration-kit/src/integration-rpc.ts +++ b/packages/integration-kit/src/integration-rpc.ts @@ -107,13 +107,20 @@ export function createIntegrationRpc(options: IntegrationRpcOptions) { handlers.installHost = () => installHost() handlers.hosts = async () => registry.hosts() handlers.attachHost = async (input, context) => { - const { offerID, sessionID } = input as { offerID: string; sessionID: string } - return bindings.attach(offerID, sessionID, context?.signal) + const { offerID, sessionID, takeover } = input as { offerID: string; sessionID: string; takeover?: boolean } + return bindings.attach(offerID, sessionID, context?.signal, takeover) } handlers.detachHost = async (input, context) => bindings.detach((input as { sessionID: string }).sessionID, context?.signal) handlers.bindingRead = (input, context) => bindings.read(input, context?.signal) - handlers.advertise = (input) => registry.advertise(input) + handlers.advertise = async (input) => { + const result = await registry.advertise(input) + return result.outcome !== "refused" && + process.versions.bun && + !/^bun(?:\.exe)?$/i.test(process.execPath.split(/[/\\]/).at(-1) ?? "") + ? { ...result, panel_runtime: process.execPath } + : result + } handlers.withdraw = async (input) => registry.withdraw(input) } diff --git a/packages/integration-kit/src/offer-registry.ts b/packages/integration-kit/src/offer-registry.ts index 037b539..1b47f8d 100644 --- a/packages/integration-kit/src/offer-registry.ts +++ b/packages/integration-kit/src/offer-registry.ts @@ -59,7 +59,7 @@ export type OfferRegistry = { advertise(input: unknown): Promise<{ outcome: AdvertiseOutcome }> withdraw(input: unknown): { outcome: WithdrawOutcome } hosts(): { offers: HostOffer[] } - attach(offerID: string, sessionID: string): { outcome: AttachOutcome } + attach(offerID: string, sessionID: string, takeover?: boolean): { outcome: AttachOutcome; replaced?: boolean } detach(sessionID: string): { outcome: "detached" | "none" } binding(sessionID: string): HostBinding | null liveHellos(): LiveHello[] @@ -315,7 +315,7 @@ export function createOfferRegistry(options: OfferRegistryOptions): OfferRegistr } }, - attach(offerID, sessionID) { + attach(offerID, sessionID, takeover) { if (!active()) return { outcome: "refused" } if (typeof sessionID !== "string" || !SESSION_ID.test(sessionID)) return { outcome: "refused" } if (typeof offerID !== "string" || !OFFER_ID.test(offerID)) return { outcome: "gone" } @@ -325,11 +325,11 @@ export function createOfferRegistry(options: OfferRegistryOptions): OfferRegistr if (record.compatibility === "incompatible") return { outcome: "refused" } const bound = sessions.get(sessionID) if (bound === offerID) return { outcome: "attached" } - if (bound !== undefined) return { outcome: "busy" } - if (sessions.size >= MAX_SESSIONS) return { outcome: "refused" } + if (bound !== undefined && !takeover) return { outcome: "busy" } + if (bound === undefined && sessions.size >= MAX_SESSIONS) return { outcome: "refused" } sessions.set(sessionID, offerID) changed("status") - return { outcome: "attached" } + return bound !== undefined ? { outcome: "attached", replaced: true } : { outcome: "attached" } }, detach(sessionID) { diff --git a/packages/integration-kit/src/panel-pipes.ts b/packages/integration-kit/src/panel-pipes.ts index 09c29c7..598a190 100644 --- a/packages/integration-kit/src/panel-pipes.ts +++ b/packages/integration-kit/src/panel-pipes.ts @@ -4,6 +4,7 @@ import { createPanel, type PanelHost, type PanelRequest } from "./panel.ts" import { discoverService } from "./panel-service.ts" export function runPanel(config: PanelHost) { + delete process.env.BUN_BE_BUN const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) const panel = createPanel(config, { send, @@ -12,7 +13,6 @@ export function runPanel(config: PanelHost) { return endpoint && OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers, fetch: endpoint.fetch }) }, }) - const queues = new Map>() const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) input.on("line", (line) => { if (!line.trim()) return @@ -20,18 +20,12 @@ export function runPanel(config: PanelHost) { if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") const request = JSON.parse(line) as PanelRequest if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") - const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => panel.dispatch(request)) - queues.set(request.channel, next) - void next.finally(() => { - if (queues.get(request.channel) === next) queues.delete(request.channel) - }) + void panel.dispatch(request) } catch { send({ error: { message: "Invalid panel request." } }) } }) input.on("close", () => { - // Blender can close its pipe while Connect is pending. Detach if that Connect reaches the service. - const closed = config.consoleEvents ? Promise.allSettled(queues.values()).then(panel.closeAll) : panel.closeAll() - void closed.finally(() => process.exit(0)) + void panel.closeAll().finally(() => process.exit(0)) }) } diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts index a351bda..4e82c02 100644 --- a/packages/integration-kit/src/panel.ts +++ b/packages/integration-kit/src/panel.ts @@ -1,4 +1,6 @@ // An in-app chat is a plain client: attach its conversation to the host's existing offer, never announce one. + +import { basename, normalize } from "node:path" import type { OpenCode } from "@opencode/client" import { rpcDefinition } from "./contract.ts" import { requestHost as kitRequestHost } from "./host-client.ts" @@ -19,22 +21,28 @@ type Channel = { offerID: string host: { host: string; port: number; token: string } handle: string + rpc: Rpc abort: AbortController - timer?: NodeJS.Timeout - checking: boolean - tools: Map + tools: Map model?: ModelRef } +type Target = { + id: string + params?: Record + fresh?: boolean + empty?: boolean + selected?: string + taken?: boolean + pending: string[] + problem?: string + retry?: NodeJS.Timeout +} export type PanelRequest = { id: string; channel: string; method: string; params?: Record } export type PanelHost = { app: string rpcID: string - marker: string document: string - keyField: string - nameField: string - defaultName: string duplicateOffer: string agent?: boolean consoleEvents?: boolean @@ -45,12 +53,25 @@ export type PanelDependencies = { discover: (registration?: string) => Promise send: (message: unknown) => void requestHost?: typeof kitRequestHost - offerWaitMs?: number checkEveryMs?: number + retryMs?: number } // A message of this sidecar's own, safe to show in the panel. class PanelError extends Error {} +class WaitingForOffer extends Error {} + +function innerTools(input: unknown) { + const code = (input as { code?: unknown } | null)?.code + if (typeof code !== "string") return undefined + const names = new Set( + Array.from( + code.matchAll(/\btools\.(\w+)(?:\.(\w+)|\[['"]([\w-]+)['"]\])\s*\(/g), + ([, ns, dot, key]) => `${ns}_${dot ?? key}`, + ), + ) + return names.size ? [...names].join(", ") : undefined +} // An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. export function briefly(error: unknown) { @@ -68,9 +89,18 @@ const modelKey = (model: ModelRef | undefined) => type Part = { type?: string; text?: string; name?: string; state?: { status?: string } } type Message = { type?: string; text?: string; content?: Part[] } +type Conversation = { id: string; title?: string; time?: { updated?: number } } + +function conversationEntry({ id, title, time }: Conversation) { + const minutes = time?.updated ? Math.max(0, Math.floor((Date.now() - time.updated) / 60_000)) : 0 + const age = + minutes >= 1440 ? `${Math.floor(minutes / 1440)}d` : minutes >= 60 ? `${Math.floor(minutes / 60)}h` : `${minutes}m` + return { id, title: `${title || "Untitled"} (${age} ago)` } +} type EventData = { sessionID?: string delta?: string + input?: unknown id?: string name?: string action?: string @@ -94,10 +124,11 @@ function history(messages: ReadonlyArray) { export function createPanel(config: PanelHost, deps: PanelDependencies) { const requestHost = deps.requestHost ?? kitRequestHost - // A Location opened for the panel loads its plugins first, which took tens of seconds in a trial. - const offerWaitMs = deps.offerWaitMs ?? 30_000 const checkEveryMs = deps.checkEveryMs ?? 5_000 const channels = new Map() + const targets = new Map() + const queues = new Map>() + let stopping = false let client: Api | undefined let registration: string | undefined let rpc: Rpc = {} @@ -114,7 +145,7 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { async function api() { if (client) return client const found = await deps.discover(registration) - if (!found) throw new PanelError("Start OpenCode before connecting the panel.") + if (!found) throw new PanelError("Start OpenCode to use this conversation.") client = found rpc = found.rpc(rpcDefinition(config.rpcID, "native") as never) as unknown as Rpc return client @@ -122,67 +153,67 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { // This project's offer: the one with its label among the offered hosts (offer keys stay private to the service). async function findOffer(c: { directory: string; label: string }) { - const until = Date.now() + offerWaitMs - for (;;) { - let result: { offers?: unknown } | undefined - try { - result = (await rpc.hosts?.({}, options(c))) as typeof result - } catch (error) { - // The first call in the project's folder: OpenCode opens that Location and loads its plugins meanwhile, and - // the integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). - if ( - !/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || - Date.now() > until - ) - throw error - await new Promise((resolve) => setTimeout(resolve, 1_000)) - continue - } - const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( - (offer) => offer.label === c.label, - ) - if (offers.length > 1) - throw new PanelError( - `Several ${config.duplicateOffer} offer ${c.label}: attach this conversation from OpenCode (${config.app.toLowerCase()}_hosts).`, - ) - if (offers[0]) return offers[0] - if (Date.now() > until) - throw new PanelError(`This ${config.document} is not offered to OpenCode yet; choose Connect again.`) - await new Promise((resolve) => setTimeout(resolve, 1_000)) + let result: Record | undefined + try { + result = await rpc.hosts?.({}, options(c)) + } catch (error) { + // A new Location may still be loading its plugins. + if (/RPC is unavailable|timed out|TimeoutError/i.test(briefly(error))) throw new WaitingForOffer() + throw error } + const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( + (offer) => offer.label === c.label, + ) + if (offers.length > 1) + throw new PanelError(`Several ${config.duplicateOffer} offer ${c.label}; this panel cannot pick one.`) + if (!offers[0]) throw new WaitingForOffer() + return offers[0] } async function attached(c: Channel) { - const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) + const read = await c.rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) return read?.state === "attached" && (read.binding as { offerID?: string } | undefined)?.offerID === c.offerID } - // The project's own conversation, when one is marked for it and still open. - async function markedSession(service: Api, directory: string, key: string) { + async function folderSessions(service: Api, directory: string) { let cursor: string | undefined - for (let page = 0; page < 10; page += 1) { - const listed = await service.session.list({ directory, order: "desc", limit: 100, cursor }) - const found = listed.data.find( - (candidate) => - !candidate.time?.archived && - (candidate.metadata as Record | undefined)?.[config.marker] === key, + const sessions = [] + do { + const listed = await service.session.list({ directory, archived: false, order: "desc", limit: 100, cursor }) + sessions.push( + ...listed.data.filter( + (candidate) => + !candidate.time?.archived && + (!candidate.location || folderKey(candidate.location.directory) === folderKey(directory)), + ), ) - if (found) return found cursor = listed.cursor.next ?? undefined - if (!cursor) return undefined - } - return undefined + } while (cursor) + return sessions.sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0)) + } + + function folderKey(path: unknown) { + const key = normalize(String(path ?? "")).replace(/[/\\]$/, "") + return process.platform === "win32" ? key.toLowerCase() : key + } + + async function conversationList(target: Target, directory: string) { + const sessions = await folderSessions(await api(), directory) + event(target, "conversations", { + selected: target.selected, + entries: sessions.map(conversationEntry), + }) + return sessions } // Closing releases this panel's conversation only: the offer stays for every other conversation. async function close(c: Channel) { if (channels.get(c.id) === c) channels.delete(c.id) - if (c.timer) clearInterval(c.timer) c.abort.abort() - await host(c, "cancel").catch(() => {}) + if ([...channels.values()].some((other) => other.sessionID === c.sessionID && other.offerID === c.offerID)) return // Another client may have moved the conversation to another host: never detach that binding. await attached(c) - .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) + .then((still) => (still ? c.rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) .catch(() => {}) } @@ -200,13 +231,19 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { else if (type === "session.text.ended") event(c, "assistant_end", {}) else if (type === "session.tool.input.started") { c.tools.set(String(data.id), { name: String(data.name ?? "tool"), started: performance.now() }) - event(c, "tool", { id: data.id, name: data.name, state: "starting" }) + if (data.name !== "execute") event(c, "tool", { id: data.id, name: data.name, state: "starting" }) + } else if (type === "session.tool.called") { + const tool = c.tools.get(String(data.id)) + if (tool?.name === "execute") { + tool.inner = innerTools(data.input) + event(c, "tool", { id: data.id, name: tool.inner ?? tool.name, state: "starting" }) + } } else if (type === "session.tool.success" || type === "session.tool.failed") { const tool = c.tools.get(String(data.id)) c.tools.delete(String(data.id)) event(c, "tool", { id: data.id, - name: tool?.name, + name: tool?.inner ?? tool?.name, state: type === "session.tool.success" ? "completed" : "failed", ...(config.consoleEvents && tool ? { duration_ms: Math.round(performance.now() - tool.started) } : {}), }) @@ -234,36 +271,13 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { } catch { // ended below } - if (!c.abort.signal.aborted) - event(c, config.consoleEvents ? "disconnected" : "error", { - message: "OpenCode disconnected; choose Connect to reconnect.", + if (!c.abort.signal.aborted) { + void serialize(c.id, async () => { + if (channels.get(c.id) !== c) return + const target = targets.get(c.id) + if (target) await reconnect(target, c) }) - } - - function watch(c: Channel) { - let warned = false - c.timer = setInterval(() => { - if (c.checking) return - c.checking = true - void api() - .then(() => attached(c)) - .then((still) => { - if (!still) throw new Error("detached") - warned = false - }) - .catch(() => { - client = undefined - if (!warned && channels.get(c.id) === c) - event(c, config.consoleEvents ? "disconnected" : "error", { - message: "Conversation detached or service unavailable; choose Connect to reconnect.", - }) - warned = true - }) - .finally(() => { - c.checking = false - }) - }, checkEveryMs) - c.timer.unref?.() + } } // A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. @@ -271,67 +285,75 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { try { return await work() } catch (error) { - if (error instanceof PanelError) throw error - throw new PanelError( - `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - ) + if (error instanceof PanelError || error instanceof WaitingForOffer) throw error + throw new PanelError(`Could not connect while ${doing}: ${briefly(error)}`) } } - async function connect(id: string, params: Record, fresh: boolean) { + async function connect(target: Target, params: Record) { + const id = target.id const previous = channels.get(id) if (previous) await close(previous) + if (!params.token || !params.offer_label) throw new WaitingForOffer() if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) throw new Error("Invalid host endpoint.") const directory = String(params.directory ?? "") const label = String(params.offer_label ?? "") - const key = String(params[config.keyField] ?? "") const handle = String(params.script_handle ?? "") - if (!directory || !label || !key || !handle) throw new Error("Incomplete connect request.") - if (config.hostControls === false) { - const next = typeof params.registration === "string" ? params.registration : undefined - if (next !== registration) client = undefined - registration = next - } + if (!directory || !label || !handle) throw new Error("Incomplete connect request.") + const next = typeof params.registration === "string" ? params.registration : undefined + if (next !== registration) client = undefined + registration = next const service = await step("reaching OpenCode", api) + const currentRpc = service.rpc(rpcDefinition(config.rpcID, "native") as never) as unknown as Rpc + const offer = await step(`finding this ${config.document}'s offer`, () => findOffer({ directory, label })) // The project's conversation, unless New asked for another one. - const known = fresh - ? undefined - : await step(`finding this ${config.document}'s conversation`, () => markedSession(service, directory, key)) + const sessions = await step("listing conversations in this folder", () => folderSessions(service, directory)) + const known = target.fresh ? undefined : (sessions.find((s) => s.id === target.selected) ?? sessions[0]) + if (!known && !target.pending.length) { + if (!target.empty) { + target.empty = true + event(target, "session", { id: null, draft: Boolean(target.fresh), workspace: directory }) + event(target, "history", { messages: [] }) + event(target, "conversations", { + entries: sessions.map(conversationEntry), + }) + event(target, "status", { state: "idle" }) + } + return + } const session = known ?? (await step(`creating this ${config.document}'s conversation`, () => service.session.create({ - title: `${config.app}: ${String(params[config.nameField] || config.defaultName)}`, + title: `${config.app}: ${basename(directory) || directory}`, location: { directory }, - metadata: { [config.marker]: key }, }), )) + target.fresh = false + target.empty = false + target.selected = session.id const c: Channel = { id, directory, sessionID: session.id, label, - offerID: "", + offerID: offer.offerID, host: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, handle, + rpc: currentRpc, abort: new AbortController(), - checking: false, tools: new Map(), model: (session as { model?: ModelRef }).model, } try { - const offer = await step(`finding this ${config.document}'s offer`, () => findOffer(c)) const result = await step(`attaching the conversation to this ${config.document}`, async () => - rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), + c.rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID, takeover: true }, options(c)), ) if (result?.outcome === "busy") throw new PanelError("This conversation is attached to another application; detach it there first.") if (result?.outcome !== "attached") throw new PanelError(`${config.app} attachment was refused.`) - c.offerID = offer.offerID channels.set(id, c) - watch(c) - void stream(c, service) const [messages, models, configured, active] = await step("loading the conversation", () => Promise.all([ service.message.list({ sessionID: c.sessionID, order: "desc", limit: 200 }), @@ -355,9 +377,15 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), }) event(c, "history", { messages: history([...messages.data].reverse() as never) }) + event(target, "conversations", { + selected: session.id, + entries: (known ? sessions : [session, ...sessions]).map(conversationEntry), + }) + if (result.replaced) event(c, "notice", { message: "Conversation moved from another host to this one." }) event(c, "status", { state: (active as Record)[c.sessionID]?.type === "running" ? "busy" : "idle", }) + void stream(c, service) } catch (error) { await close(c) throw error @@ -370,10 +398,6 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { if (method === "interrupt") { await host(c, "cancel").catch(() => {}) await service.session.interrupt({ sessionID: c.sessionID, resume: false }) - } else if (method === "prompt") { - if (!(await attached(c))) throw new PanelError(`${config.app} was detached; choose Connect to attach again.`) - await host(c, "resume") - await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) } else if (method === "switch_model") { const key = String(params.model ?? "") const catalog = await service.model.list({ location: { directory: c.directory } }) @@ -389,15 +413,148 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { } else throw new Error("Unknown panel action.") } - async function dispatch(request: PanelRequest) { + function serialize(id: string, work: () => Promise) { + if (stopping) return Promise.resolve() + const next = (queues.get(id) ?? Promise.resolve()).then(work) + queues.set(id, next) + void next + .finally(() => { + if (queues.get(id) === next) queues.delete(id) + }) + .catch(() => {}) + return next + } + + function later(target: Target, ms: number) { + clearTimeout(target.retry) + if (stopping) return + target.retry = setTimeout(() => { + void serialize(target.id, async () => { + if (targets.get(target.id) !== target) return + const c = channels.get(target.id) + if (c && !(await attached(c).catch(() => false))) await reconnect(target, c) + else await reconcile(target) + }) + }, ms) + target.retry.unref?.() + } + + async function reconnect(target: Target, c: Channel) { + const read = await c.rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)).catch(() => undefined) + if (read?.state === "attached" && (read.binding as { offerID?: string }).offerID !== c.offerID) { + // Do not steal it back from the host whose user just opened it. + target.taken = true + await close(c) + event(target, "status", { state: "connecting" }) + event(target, "notice", { message: "Conversation moved to another host. Open it again here to take it back." }) + return + } + event(target, "status", { state: "connecting" }) + await close(c) + client = undefined + later(target, deps.retryMs ?? 1_000) + } + + async function reconcile(target: Target) { + if (!target.params || target.taken || stopping) return + let c = channels.get(target.id) + if (!c) { + try { + await connect(target, target.params) + target.problem = undefined + } catch (error) { + client = undefined + if (!(error instanceof WaitingForOffer)) { + const message = error instanceof PanelError ? error.message : `Could not connect: ${briefly(error)}` + if (message !== target.problem) event(target, "error", { message }) + target.problem = message + } + } + c = channels.get(target.id) + } + if (!c) { + if (!target.empty || target.pending.length) later(target, deps.retryMs ?? 1_000) + return + } + later(target, checkEveryMs) + while (target.pending.length) { + if (!(await attached(c).catch(() => false))) return await reconnect(target, c) + try { + await host(c, "resume") + } catch { + return later(target, deps.retryMs ?? 1_000) + } + const text = target.pending.shift() as string + event(target, "user_message", { text }) + try { + await (await api()).session.prompt({ sessionID: c.sessionID, text }) + } catch (error) { + // Delivery is uncertain once submitted: never replay automatically. + event(target, "error", { message: `Message delivery could not be confirmed: ${briefly(error)}` }) + } + } + } + + async function handle(request: PanelRequest) { try { const params = request.params ?? {} - if (request.method === "connect" || request.method === "new_session") - await connect(request.channel, params, request.method === "new_session") - else { - const c = channels.get(request.channel) - if (c) await act(c, request.method, params) - else if (request.method !== "close") throw new PanelError("Choose Connect first.") + const id = request.channel + const target = targets.get(id) ?? { id, pending: [] } + const c = channels.get(id) + if (request.method === "close") { + clearTimeout(target.retry) + targets.delete(id) + if (c) await close(c) + } else { + targets.set(id, target) + if (request.method === "list" && target.params) { + await conversationList(target, String(target.params.directory)) + } else if (request.method === "open" && target.params) { + const sessions = await folderSessions(await api(), String(target.params.directory)) + const selected = sessions.find((s) => s.id === params.session_id) + if (!selected) throw new PanelError("That conversation is not in this folder.") + target.selected = selected.id + target.taken = false + target.fresh = false + target.pending = [] + if (c?.sessionID !== selected.id) { + event(target, "status", { state: "connecting" }) + if (c) await close(c) + await reconcile(target) + } + } else if (request.method === "connect" || request.method === "new_session") { + const fresh = request.method === "new_session" + const moved = target.params && folderKey(target.params.directory) !== folderKey(params.directory) + if (moved) target.selected = undefined + if (!target.params) { + if (typeof params.session_id === "string") target.selected = params.session_id + target.fresh = params.draft === true + } + if (fresh || moved) { + if (target.pending.length) + event(target, "notice", { message: "Queued messages were not sent to the new conversation." }) + target.pending = [] + } + target.params = params + if (fresh || moved) { + target.selected = undefined + target.fresh = fresh + target.empty = false + } else if (target.empty) { + target.empty = false + } + target.taken = false + target.problem = undefined + event(target, "status", { state: "connecting" }) + if (c) await close(c) + await reconcile(target) + } else if (request.method === "prompt") { + target.pending.push(String(params.text ?? "")) + if (target.params) await reconcile(target) + } else if (request.method === "interrupt") { + target.pending = [] + if (c) await act(c, request.method, params) + } else if (c) await act(c, request.method, params) } deps.send({ id: request.id, result: {} }) } catch (error) { @@ -405,10 +562,7 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { channel: request.channel, event: "error", data: { - message: - error instanceof PanelError - ? error.message - : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, + message: error instanceof PanelError ? error.message : `The panel action failed: ${briefly(error)}`, }, }) deps.send({ id: request.id, error: { message: "Panel action failed." } }) @@ -416,7 +570,12 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { } return { - dispatch, - closeAll: () => Promise.allSettled([...channels.values()].map(close)), + dispatch: (request: PanelRequest) => serialize(request.channel, () => handle(request)), + closeAll: async () => { + stopping = true + for (const target of targets.values()) clearTimeout(target.retry) + await Promise.allSettled(queues.values()) + await Promise.allSettled([...channels.values()].map(close)) + }, } } diff --git a/packages/integration-kit/src/session-bindings.ts b/packages/integration-kit/src/session-bindings.ts index 0e15276..3a04fa0 100644 --- a/packages/integration-kit/src/session-bindings.ts +++ b/packages/integration-kit/src/session-bindings.ts @@ -73,10 +73,10 @@ export function createSessionBindings(registry: OfferRegistry, native?: NativeSe return parseBindingReadOutput(registry.read(parsed.sessionID)) ?? { state: "unknown" } } - const attach = async (offerID: string, sessionID: string, signal?: AbortSignal) => { + const attach = async (offerID: string, sessionID: string, signal?: AbortSignal, takeover?: boolean) => { const authority = await snapshot(sessionID, signal) return authority && !signal?.aborted && registry.current(authority) - ? registry.attach(offerID, sessionID) + ? registry.attach(offerID, sessionID, takeover) : { outcome: "refused" as const } } const detach = async (sessionID: string, signal?: AbortSignal) => { diff --git a/packages/integration-kit/test/panel.test.ts b/packages/integration-kit/test/panel.test.ts new file mode 100644 index 0000000..dfd37a8 --- /dev/null +++ b/packages/integration-kit/test/panel.test.ts @@ -0,0 +1,154 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { it } from "node:test" +import { setTimeout as delay } from "node:timers/promises" +import { type Api, createPanel } from "../src/panel.ts" + +it("the Python hosts prefer the advertised executable over either Node fallback", () => { + const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") + const result = spawnSync(python, ["-I", join(import.meta.dirname, "panel_launcher_test.py")], { + encoding: "utf8", + windowsHide: true, + }) + assert.equal(result.status, 0, result.error?.message ?? result.stderr) +}) + +it("queues during startup, starts drafts lazily and selects/rebinds folder conversations", async () => { + const directory = join(tmpdir(), "shot") + const other = join(tmpdir(), "other") + const prompt: unknown[] = [] + const attached = new Map() + const sessions: Array<{ + id: string + title: string + location: { directory: string } + time: { updated: number; archived?: number } + }> = [] + let label = "" + let offer = "offer-a" + const out: { event: string; data: Record }[] = [] + const api = { + rpc: () => ({ + hosts: async () => ({ offers: label ? [{ label, offerID: offer }] : [] }), + attachHost: async ({ + offerID, + sessionID, + takeover, + }: { + offerID: string + sessionID: string + takeover: boolean + }) => { + assert.equal(takeover, true) + const replaced = attached.has(sessionID) && attached.get(sessionID) !== offerID + attached.set(sessionID, offerID) + return { outcome: "attached", replaced } + }, + bindingRead: async ({ sessionID }: { sessionID: string }) => + attached.has(sessionID) + ? { state: "attached", binding: { offerID: attached.get(sessionID) } } + : { state: "none" }, + detachHost: async ({ sessionID }: { sessionID: string }) => attached.delete(sessionID), + }), + session: { + list: async () => ({ data: sessions, cursor: {} }), + create: async ({ title, location }: { title: string; location: { directory: string } }) => { + const item = { id: `created-${sessions.length}`, title, location, time: { updated: 100 } } + sessions.push(item) + return item + }, + prompt: async (item: unknown) => prompt.push(item), + active: async () => ({}), + }, + model: { list: async () => ({ data: [] }), default: async () => ({}) }, + message: { list: async () => ({ data: [] }) }, + event: { + subscribe: async function* ({ signal }: { signal: AbortSignal }) { + await new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true })) + }, + }, + } as unknown as Api + const panel = createPanel( + { app: "Test", rpcID: "neuralnomads.test", document: "scene", duplicateOffer: "hosts" }, + { + discover: async () => api, + send: (value) => out.push(value as (typeof out)[number]), + requestHost: async () => ({}), + retryMs: 3, + checkEveryMs: 10, + }, + ) + const params = (offer_label: string, dir = directory) => ({ + host: "127.0.0.1", + port: 5555, + token: "a".repeat(64), + script_handle: offer_label, + offer_label, + directory: dir, + }) + const call = (method: string, params?: Record, channel = "panel") => + panel.dispatch({ id: method, channel, method, params }) + const until = async (condition: () => boolean) => { + for (let i = 0; i < 200; i++) { + if (condition()) return + await delay(5) + } + assert.fail("Panel did not reach the expected state") + } + const current = () => out.filter((item) => item.event === "session").at(-1)?.data.id + try { + await call("connect", params("v001")) + assert.equal( + out.some((item) => item.event === "error"), + false, + ) + assert.equal(sessions.length, 0) + await call("prompt", { text: "early" }) + assert.equal(prompt.length, 0) + label = "v001" + await until(() => prompt.length === 1) + assert.equal(sessions[0]?.title, "Test: shot") + assert.deepEqual(prompt[0], { sessionID: "created-0", text: "early" }) + + sessions.push( + { id: "codenomad", title: "CodeNomad", location: { directory }, time: { updated: 200 } }, + { id: "archived", title: "Archived", location: { directory }, time: { updated: 300, archived: 301 } }, + { id: "different", title: "Different", location: { directory: other }, time: { updated: 400 } }, + ) + label = "v002" + await call("connect", params(label)) + assert.equal(current(), "created-0") + await call("list") + assert.deepEqual( + ((out.findLast((item) => item.event === "conversations")?.data.entries ?? []) as { id: string }[]).map( + ({ id }) => id, + ), + ["codenomad", "created-0"], + ) + attached.set("codenomad", "other-host") + await call("open", { session_id: "codenomad" }) + assert.equal(current(), "codenomad") + assert.equal(attached.get("codenomad"), offer) + assert.match(String(out.findLast((item) => item.event === "notice")?.data.message), /moved from another host/) + await call("new_session", params(label)) + assert.equal(current(), null) + assert.equal(sessions.length, 4) + await call("prompt", { text: "first in draft" }) + assert.equal(sessions.length, 5) + assert.equal(current(), "created-4") + attached.delete("created-4") + offer = "offer-restarted" + await until(() => attached.get("created-4") === offer) + await call("connect", params(label, other)) + assert.equal(current(), "different") + await call("connect", params(label), "newly-opened") + assert.equal(current(), "codenomad") + await call("connect", params(label, join(tmpdir(), "empty"))) + assert.equal(current(), null) + assert.equal(sessions.length, 5) + } finally { + await panel.closeAll() + } +}) diff --git a/packages/integration-kit/test/panel_launcher_test.py b/packages/integration-kit/test/panel_launcher_test.py new file mode 100644 index 0000000..2869a85 --- /dev/null +++ b/packages/integration-kit/test/panel_launcher_test.py @@ -0,0 +1,28 @@ +import os +from pathlib import Path +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "python")) +from opencode_service import panel_launcher + + +class LauncherTests(unittest.TestCase): + def test_selection_order_and_fallback(self): + override = "TEST_NODE" + advertised = os.path.abspath("opencode") + accepted = {"outcome": "accepted", "panel_runtime": advertised} + with patch.dict(os.environ, {override: "custom"}), patch("shutil.which") as which: + which.side_effect = lambda candidate: candidate + self.assertEqual(panel_launcher([accepted], override), (advertised, True)) + which.assert_called_once_with(advertised) + self.assertEqual(panel_launcher([], override), ("custom", False)) + which.side_effect = lambda candidate: "node" if candidate == "node" else None + self.assertEqual(panel_launcher([accepted], override), ("node", False)) + which.side_effect = lambda _: None + self.assertEqual(panel_launcher([accepted], override), (None, False)) + + +if __name__ == "__main__": + unittest.main() From 97c0c2694191bd0fac525e9d58462072f9bae8d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:39:03 +0100 Subject: [PATCH 04/13] Keep chat streams on scene renames and prefer the advertised runtime --- .../host/opencode_link/_console_opencode.py | 13 +++-- .../host/opencode_link/opencode_service.py | 4 +- .../host/blender/opencode_link-0.4.8.zip | Bin 998661 -> 999776 bytes integrations/blender/plugin/package.json | 2 +- .../host/python/GafferOpenCodeUI/Client.py | 11 ++-- .../host/gaffer/opencode_link-0.3.0.zip | Bin 261978 -> 262923 bytes integrations/gaffer/plugin/package.json | 2 +- integrations/gaffer/test/panel_probe.py | 2 +- .../godot/host/addons/opencode_link/dock.gd | 11 +++- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 189665 -> 190576 bytes integrations/godot/plugin/package.json | 2 +- integrations/godot/test/godot.test.ts | 2 +- .../host/scripts/opencode_houdini/panel.py | 11 ++-- .../host/houdini/opencode_link-0.3.1.zip | Bin 252881 -> 253844 bytes integrations/houdini/plugin/package.json | 2 +- integrations/houdini/test/panel_probe.py | 8 +-- .../python/opencode_service.py | 4 +- packages/integration-kit/src/panel.ts | 48 +++++++++++++----- 18 files changed, 86 insertions(+), 36 deletions(-) diff --git a/integrations/blender/host/opencode_link/_console_opencode.py b/integrations/blender/host/opencode_link/_console_opencode.py index 576f6bb..f714f46 100644 --- a/integrations/blender/host/opencode_link/_console_opencode.py +++ b/integrations/blender/host/opencode_link/_console_opencode.py @@ -109,6 +109,7 @@ def __init__(self): self.active = False self.problem = "" self.retry_at = 0 + self.launch_at = time.monotonic() + 5 self.state, self.agent, self.model = "Connecting", "", "" def send(self, method, **params): @@ -189,6 +190,8 @@ def output(text="", end=False): elif name == "notice": append("INFO", data["message"]) elif name == "session": + if data.get("draft") and not self.draft: + append("CLEAR", "") self.selected = data["id"] self.draft = data.get("draft", False) self.state, self.agent, self.model = "Ready", data.get("agent"), data.get("model") @@ -243,7 +246,10 @@ def output(text="", end=False): def _append(kind, text): - bpy.ops.console.scrollback_append(text=text, type=kind) + if kind == "CLEAR": + bpy.ops.console.clear(scrollback=True, history=False) + else: + bpy.ops.console.scrollback_append(text=text, type=kind) def _areas(): @@ -305,14 +311,15 @@ def _sync(append): )) if not chat.pipes: services = host.advertiser.results if host and host.advertiser else [] - launcher = panel_launcher(services, "NEURALNOMADS_BLENDER_NODE") + waiting = time.monotonic() < chat.launch_at + launcher = panel_launcher(services, "NEURALNOMADS_BLENDER_NODE", wait=waiting) if launcher[0]: chat.pipes = Pipes(launcher) chat.send("connect", **chat.target, session_id=chat.selected, draft=chat.draft) for params in chat.unsent: chat.send("prompt", **params) chat.unsent.clear() - elif services: + elif not waiting: chat.blocked("No OpenCode runtime, NEURALNOMADS_BLENDER_NODE executable, or Node on PATH.", append) diff --git a/integrations/blender/host/opencode_link/opencode_service.py b/integrations/blender/host/opencode_link/opencode_service.py index 25451a0..41c5eca 100644 --- a/integrations/blender/host/opencode_link/opencode_service.py +++ b/integrations/blender/host/opencode_link/opencode_service.py @@ -250,12 +250,14 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env return results -def panel_launcher(results, override): +def panel_launcher(results, override, wait=False): """Use the daemon's advertised executable, then the host override, then Node on PATH.""" for result in results: runtime = result.get("panel_runtime") if result.get("outcome") in ("accepted", "renewed") and isinstance(runtime, str) and os.path.isabs(runtime) and shutil.which(runtime): return runtime, True + if wait and not any(result.get("outcome") in ("accepted", "renewed") for result in results): + return None, False for candidate in (os.environ.get(override), "node"): if candidate and (node := shutil.which(candidate)): return node, False diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index c6a510fd7c5d8e8db91d559ce6b1fcc243718959..39a8306436abffb3e9e5e0dafe8b6076f772463f 100644 GIT binary patch delta 2150 zcmZ8idu$X%7~k6~z3tvy=ST}JQeb+Odd2JZK?`l~uBC`5iljyG5v;h}?a{N>-E((a zJj5s>0!l=!_-O!*3Qbf3pz z-+N|vPeeu@i@ts5Q{uq6OJloMa@?+!gYr{P_;OQnj~eUj8~t$}UoZCEb5t4>UUGZO zlL;1=OYRK!^ok_E=uw zp#NwluMKr{CGki!$^y=QlgK82ThbXxOB+&5Qw=SpNU@Y6>p>%?YpK*0Io1{3p!X;t z)|oU+P0vJE%PB*F(`s(v;Jy<_1yY}6i^Fz$0 zL??NJsdr0VUfcCaVAnxw&q2$D!lSrRa!_WW`1e84Mpe5$JMAuMixTuojiYl!W zC&d@9^G<5Fy|Pw~i1)e*F;-jkbc$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!iIXhi{Fz-`*A0si(n>BLCH7PE%H2Rw2!WXb# z;A*ZvP#-w#Hx(L>s>b+=QcZTFDH@DOFE``)<2((I^m7#pecXUikp$*fIAO7$JGJ+N z+{d-bbDZRVJv0B;6L%*026T;aLzdBPjF%bDWQynS)?OUrD>BZ{@?7oAMZSa1&T<)P z5uV#?p5X!p%{;Siwd@x6Zcujqi-D7BXmKZj%EuL=y$G9z-VSd z1}=#&w!HvXE#%T$cP5}`SHc6>WEJeT{n%@z3iiDQSZOP3eGrRQaoA|KY_MV;d8PX zp;FQ2?MpC}Q#PKOk~1(;PN~Q*6OE*XWAw>U#em!~g~zo1sP<(frY(;t>G*3_j%zDX zjpm}-J~r}UEM{t4NkQtzv6uq=;2kHXt;-Gs<#X;Y4 ziazT;0=cLxIkYI`mV+&UnAYeL+MpgUxWuSG@4%c(RDCrEcU3KvC~V)_fSsu-OH?#QvS1Jz<>r1 tm9oSuc*8?hx%(F`1)5vXQzUBt(Ie`!9)s+qGIk{$UN2=PRTh$P_y>)LkNW@s diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index df17e34..6e9bab5 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.4.8", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "ed8ec9be1fdb6464765a343782fe42823a6c6b3fce1e34cbc86942b88c5ba246" + "sha256": "2f78c866745c5d2bd21ede4e78fc9c1a1f14976db9fd1d68f8c0e52d25ca72ec" } } } diff --git a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py index fcad60c..e8ca9b9 100644 --- a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py +++ b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py @@ -1,5 +1,6 @@ import json import pathlib +import time import uuid import weakref @@ -35,6 +36,7 @@ def __init__( self ) : self.__stdout = b"" self.__nextRequest = 0 self.__problem = "" + self.__launchAt = time.monotonic() + 5 self.__timer = QtCore.QTimer( self.__process ) self.__timer.timeout.connect( self.__start ) self.__timer.start( 1000 ) @@ -94,15 +96,16 @@ def __start( self ) : if not self.__targets or self.__process.state() != QtCore.QProcess.NotRunning : return services = panelServices() - runtime, bun = panel_launcher( services, "NEURALNOMADS_GAFFER_NODE" ) + waiting = time.monotonic() < self.__launchAt + runtime, bun = panel_launcher( services, "NEURALNOMADS_GAFFER_NODE", wait = waiting ) # Built into the installed part, beside the Python packages. sidecar = pathlib.Path( __file__ ).resolve().parents[2] / "sidecar.cjs" problem = ( "OpenCode Link sidecar is missing; reinstall the application part." if not sidecar.is_file() else - "No OpenCode runtime, NEURALNOMADS_GAFFER_NODE executable, or Node on PATH." if not runtime else "" ) - if problem and services and problem != self.__problem : + "No OpenCode runtime, NEURALNOMADS_GAFFER_NODE executable, or Node on PATH." if not runtime and not waiting else "" ) + if problem and problem != self.__problem : self.__emitAll( "error", { "message" : problem } ) self.__problem = problem - if problem : + if problem or not runtime : return environment = QtCore.QProcessEnvironment.systemEnvironment() environment.remove( "BUN_BE_BUN" ) diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index e4938df70c28307a1dd9826b7db9d2d4cea10a6b..dd527fde6a5c8ab1dd51ca3067ab4a79545f486e 100644 GIT binary patch delta 1256 zcmZ8hQD_`R7~a__N$yfFX%lRcdhx#%;;lJX0wyWZ>k+8cd#HUWeF-sa?&gvud%MTX zZ1ikPLLVyPL$QI3kb?F_Brj?RU8sQy#rkCXAo@_zqE%?o7saSla&>0!au*y}=AVE5 z`RDuo@1MO>>w4!x_wpus^x0!*)BWnuvzn$pb0r7;VrvKYgh#f}($k$8c-?k*_PFh` z@ajGE8tQdQkqd0E2%gX7TuqCGpV7!j$)`XG3tSG4*RYs55r@X0ga_1vSACCUAj+8d z1$~L*7caf}&-p%0JKrbn-beX;+$oa~9-s@j!?gpiFh9vxMizSZ!7z-5mw!X4j&=pg z@#d8KAiM~SxFu_5W;a?~`x71Su0w}x1Xl)M-9{xevEZSmCdH*QO_BxQV;nrYOytcK zn{umeXR~0CH%KAi#DJk8Ss{frK`VMTVAYId!wIE9g_EKQ^Zb=-o(GR545xZkcy@Yxd@5GC9cfsJsq~Buqf3L?|p-l?e$e!oV<+> z=XX0*9czS1sp{5L!D56l$v%Hq7CvC>X2X|3#OqD)@D@KZX zzj$~Dr_j0Z{ag5Sm-zf;y{)f8$)e*2Oje28bdGRK_JUnzV)AR;D|WuegG&X~EX_D+ zr%LjT%`0!J>@Sj{vZjoApK)14qvF$O=Kccll!KBvhjD5v+0>d9s8iuH^YR_YvQJxN zkPMkFeQxxrXKbfBik5%m4rY delta 537 zcmeBf6S(z{zhMjG|J}S#BKXDnbr={xSaY(yg5>mEMi$}i7JC@$)wdsh%oxkKea=(H zgUq}y+APle5ocfkVMU-qiRn!*8TGdBdC6GEygm6Xqd3R(m0ua1xBvOdn8rB0=sTk{ zM{#OVS!Qx-@$`=Gj1Akxe=t6>=h|$*&M@f!BM`SUTQF^BwqQ<8nI1BmS#bKxIm`mA z1&Ku^deeW-VK&=tK9_k7-?S~vG8{@trNxy>3bormu4WEn0|`z4xtE!L`j6Gj($mkc zX6BmSw267u^qWVRxu$5=R!oo zbZ15uUs;sUW=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "3f5dddc016acc88c87ff1f969833bf7b40cda7b8e26fe66b12a3c31ee93ceaee" + "sha256": "fa7eda277d9b229a43e53748fab09b64463ea1e55cb2ddc515ecf96438cb9165" } } } diff --git a/integrations/gaffer/test/panel_probe.py b/integrations/gaffer/test/panel_probe.py index ccb10d8..7164c01 100644 --- a/integrations/gaffer/test/panel_probe.py +++ b/integrations/gaffer/test/panel_probe.py @@ -134,7 +134,7 @@ def emit(self, channel, name, data): api.__path__ = [] api.panelServices = lambda: [] service = types.ModuleType("GafferOpenCode.opencode_service") -service.panel_launcher = lambda results, override: (sys.executable, True) +service.panel_launcher = lambda results, override, wait=False: (sys.executable, True) gaffer = types.ModuleType("Gaffer") gaffer.WeakMethod = weak_method gafferui = types.ModuleType("GafferUI") diff --git a/integrations/godot/host/addons/opencode_link/dock.gd b/integrations/godot/host/addons/opencode_link/dock.gd index 235ba37..4d3a66c 100644 --- a/integrations/godot/host/addons/opencode_link/dock.gd +++ b/integrations/godot/host/addons/opencode_link/dock.gd @@ -15,6 +15,7 @@ var _pending: Array[Dictionary] = [] var _selected := "" var _draft := false var _retry_at := 0 +var _launch_at := 0 var _problem := "" var _next := 0 var _active := false @@ -159,20 +160,25 @@ static func _node() -> String: func _start() -> void: var services: Array = link.advertiser_results() var runtime := "" + var ready := false + var waiting := Time.get_ticks_msec() < _launch_at for result in services: + if not result.get("outcome") in ["accepted", "renewed"]: + continue + ready = true var advertised: String = result.get("panel_runtime", "") if advertised.is_absolute_path() and FileAccess.file_exists(advertised): runtime = advertised break var bun := runtime != "" - if not bun: + if not bun and (ready or not waiting): runtime = _node() var sidecar := ProjectSettings.globalize_path(get_script().resource_path.get_base_dir().path_join("sidecar.cjs")) if not FileAccess.file_exists(sidecar): _blocked("The OpenCode dock's sidecar is missing: install OpenCode Link again (godot_install_host).") return if runtime == "": - if not services.is_empty(): + if not waiting: _blocked("No OpenCode runtime, NEURALNOMADS_GODOT_NODE executable, or Node on PATH.") return var inherited := OS.get_environment("BUN_BE_BUN") @@ -226,6 +232,7 @@ func _process(_delta: float) -> void: if not is_visible_in_tree(): return _active = true + _launch_at = Time.get_ticks_msec() + 5000 _sync() if _stdio == null: if Time.get_ticks_msec() >= _retry_at: diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index 7c435d1d55baef5f08afab977435b1e76d1f908c..2c2bccf7e448442be28c04f1c646c47a66b3fc3e 100644 GIT binary patch delta 1258 zcmZ8hO>7%Q6wW?{7~A=&OI4={X`dI>>_*18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"36466e243f345ab9803f1e6c82d4e734fead8e1f462a47d965e53b0b57de40c3" } } } diff --git a/integrations/godot/test/godot.test.ts b/integrations/godot/test/godot.test.ts index 0fcbbbe..5c9a24f 100644 --- a/integrations/godot/test/godot.test.ts +++ b/integrations/godot/test/godot.test.ts @@ -226,7 +226,7 @@ describe("OpenCode Link in a real Godot editor", { skip: !godot, concurrency: fa it("the visible dock starts its sidecar automatically", async () => { await code( - 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.show()', + 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.reparent(EditorInterface.get_base_control())\ndock.show()', ) const transcript = await until( async () => { diff --git a/integrations/houdini/host/scripts/opencode_houdini/panel.py b/integrations/houdini/host/scripts/opencode_houdini/panel.py index 82c5cd4..9dcd4f1 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/panel.py +++ b/integrations/houdini/host/scripts/opencode_houdini/panel.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path +import time import uuid import hou @@ -11,10 +12,10 @@ import opencode_houdini -def panel_launcher(results, override): +def panel_launcher(results, override, wait=False): from .opencode_service import panel_launcher as choose - return choose(results, override) + return choose(results, override, wait=wait) def _log(message: str) -> None: @@ -45,6 +46,7 @@ def __init__(self, parent=None) -> None: self._pending: list[tuple] = [] self._targets: dict[str, dict] = {} self._problem = "" + self._launch_at = time.monotonic() + 5 self._request = 0 self._timer = QtCore.QTimer(self) self._timer.timeout.connect(self.start) @@ -54,12 +56,13 @@ def start(self) -> None: if not self._targets or self._process.state() != QtCore.QProcess.ProcessState.NotRunning: return services = opencode_houdini.panelServices() - runtime, bun = panel_launcher(services, "NEURALNOMADS_HOUDINI_NODE") + waiting = time.monotonic() < self._launch_at + runtime, bun = panel_launcher(services, "NEURALNOMADS_HOUDINI_NODE", wait=waiting) sidecar = str(Path(__file__).resolve().parents[2] / "sidecar.cjs") problem = "" if not Path(sidecar).is_file(): problem = "OpenCode Link sidecar is missing; reinstall the application part." - elif not runtime and services: + elif not runtime and not waiting: problem = "No OpenCode runtime, NEURALNOMADS_HOUDINI_NODE executable, or Node on PATH." if problem and problem != self._problem: self.diagnostic.emit(problem) diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip index b8d211f8e6e35018f53f87ac3671b77447802395..93ed70cf5ae644851aaa7a56c461530d54302dd9 100644 GIT binary patch delta 1220 zcmZuxO=uKJ6rP$ViJ8QV|Cv=IHN6mfv~B;Qhs4=jq9PkaLDs_%L)%l6X*1J3R98oX z6XPC4!ONNv>L^I?C(4e|kUj{y3VToxi3blE5ZR-!pn~E-#HyZTCW-|`z4z+X$ZEDu=DZ^sP{YK99UrwOoC~9Q_ z5jN~JwjEab(AifyQdq-ZTt`cN?K=7wmbKi>UW@dFLUP9gkLxDUi6zX+6V4{l`NdxO z=SgHP2xKfjbsKdq!8yaT&Fp}|a1u*HJ@1HUj%}H00&l^){c~lMMw+y+?7^QY?Zqz1 zW%PlXCtkUW`da5Jnm6<}O(BGuh3lXy;mY5B51k~Dne35WZ=ayh+b0($+QR-s8<6za znFyX=renJd+eV&<&;^4sy-FvOSRtp0=`o_I|k%j&$)@5mxeTMc9Kz{o_Tr-`Xnud9G?|m{E`L@?}u` zW0#<_AzHu52=IcdS1W!HYM4L%3l#o(95(WJ33|ITqU+3ZY+Tno;khH4D1;G8y#gcY z1g`eM)a8|^Umo2N{^vNv_|?m>v?GxBU`3t^?!tb7k|8P@7C7+( zGtk~xl`?ggxUOi%!QTEJosAR-j!S&0XWL>>0(`4INJL8i zY+2nTVW>9yO>g)Ye(M3m`R_ZzP5vKcI27fM8g7UcC>gdK&y^Ev&_Tjj^DL6DZnKMLeDWGJ~av3!wj*@px zY8BW(R=ik&LcdOi2^~?@Au^J{$=~DziuftP_T!|eua;sUO4NJGXCK3!(o9DyKa>c! z@c(jjs_&TWX6U4jFW4p@X0uR2=Nkm^Va3+Am+kwmfue zhXj>;dg&r4T58h4sPLqVNy#QCnbaj2+R07CpTR=Yl9JlXJ#e{j&bgfHeGpY6?!Tj; z7VFo<(FX&TwS`9WsTxk2%bM;*P5lLplX<^LWgJ@f&tG&dSk@MLa-ZE0KhIN~j}%Dr zLV@DOw@hdDndED_Lj1Ex!)D|S5d~7pxs$x1QfBNe-Bh+Hl&+4J$QmupRf27%5`;?d zf=18&$qC0D?J`6KakYC0mHWYKHBWiaI1Uh~RR2o7Y?#Sb&Ec{qnW z&nz~kj~?uHTQ)1@PPi&2Bgw=q#ok}NVVXXVV$gSPA_KI>=21.0", "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "17fb6556f0e4166341aef655a5c475f46b9844e7e7f1e68112d00ab900ce94c6" + "sha256": "2d932d8ea342e27be90e6af1cd0abd3bccf672f4da7aa8c58f7db030c89a1b57" } } } diff --git a/integrations/houdini/test/panel_probe.py b/integrations/houdini/test/panel_probe.py index 7061c98..81ecbaa 100644 --- a/integrations/houdini/test/panel_probe.py +++ b/integrations/houdini/test/panel_probe.py @@ -74,6 +74,7 @@ def test_installed_import(self): client._process = process client._targets = {"test": {}} client._problem = "" + client._launch_at = 0 qt.QtCore.QProcessEnvironment = Mock() with patch.object(panel, "panel_launcher", return_value=(sys.executable, True)): client.start() @@ -162,12 +163,13 @@ def ask(): client.send.side_effect = None # A new panel uses the same host, authority unchanged. third = panel.OpenCodePanel.__new__(panel.OpenCodePanel) - third.__dict__.update(second.__dict__, _disposed=False, _channel="third") - third._connect() + third.__dict__.update(second.__dict__, _disposed=False, _channel="third", _target=None) + integration.acquirePanel(third._channel) + third._sync() self.assertIs(integration._server, server) params = client.send.call_args.args[2] self.assertEqual(params["offer_label"], "Houdini: untitled.hip") - self.assertTrue(params["sessions_file"].endswith("panel-sessions.json")) + self.assertEqual(params["directory"], os.getcwd()) third._destroyed() self.assertTrue(server.running) finally: diff --git a/packages/integration-kit/python/opencode_service.py b/packages/integration-kit/python/opencode_service.py index 25451a0..41c5eca 100644 --- a/packages/integration-kit/python/opencode_service.py +++ b/packages/integration-kit/python/opencode_service.py @@ -250,12 +250,14 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env return results -def panel_launcher(results, override): +def panel_launcher(results, override, wait=False): """Use the daemon's advertised executable, then the host override, then Node on PATH.""" for result in results: runtime = result.get("panel_runtime") if result.get("outcome") in ("accepted", "renewed") and isinstance(runtime, str) and os.path.isabs(runtime) and shutil.which(runtime): return runtime, True + if wait and not any(result.get("outcome") in ("accepted", "renewed") for result in results): + return None, False for candidate in (os.environ.get(override), "node"): if candidate and (node := shutil.which(candidate)): return node, False diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts index 4e82c02..4fed2d5 100644 --- a/packages/integration-kit/src/panel.ts +++ b/packages/integration-kit/src/panel.ts @@ -24,6 +24,7 @@ type Channel = { rpc: Rpc abort: AbortController tools: Map + busy: boolean model?: ModelRef } type Target = { @@ -87,7 +88,7 @@ export function briefly(error: unknown) { const modelKey = (model: ModelRef | undefined) => model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" -type Part = { type?: string; text?: string; name?: string; state?: { status?: string } } +type Part = { type?: string; text?: string; name?: string; state?: { status?: string; input?: unknown } } type Message = { type?: string; text?: string; content?: Part[] } type Conversation = { id: string; title?: string; time?: { updated?: number } } @@ -116,7 +117,10 @@ function history(messages: ReadonlyArray) { if (message.type !== "assistant") return [] return (message.content ?? []).flatMap((part) => { if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] - if (part.type === "tool") return [{ role: "tool", text: `${part.name} / ${part.state?.status ?? "unknown"}` }] + if (part.type === "tool") { + const name = (part.name === "execute" && innerTools(part.state?.input)) || part.name || "tool" + return [{ role: "tool", text: `${name} / ${part.state?.status ?? "unknown"}` }] + } return [] }) }) @@ -225,7 +229,7 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { else if (config.consoleEvents && type === "session.step.started") { c.model = data.model event(c, "profile", { agent: data.agent, model: modelKey(c.model) }) - } else if (type === "session.execution.started") event(c, "status", { state: "busy" }) + } else if (type === "session.execution.started") status(c, true) else if (type === "session.text.started") event(c, "assistant_start", {}) else if (type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) else if (type === "session.text.ended") event(c, "assistant_end", {}) @@ -251,17 +255,19 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources ?? [] }) else if (config.consoleEvents && type === "permission.replied") event(c, "permission_done", { request_id: data.requestID }) - else if (type === "session.execution.succeeded" || type === "session.idle") event(c, "status", { state: "idle" }) + else if (type === "session.execution.succeeded" || type === "session.idle") status(c, false) else if (type === "session.execution.interrupted" || type === "session.execution.failed") { if (type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) - event(c, "status", { - state: "idle", - ...(config.consoleEvents && type === "session.execution.interrupted" ? { interrupted: true } : {}), - }) + status(c, false, config.consoleEvents && type === "session.execution.interrupted") void host(c, "cancel").catch(() => {}) } } + function status(c: Channel, busy: boolean, interrupted?: boolean) { + c.busy = busy + event(c, "status", { state: busy ? "busy" : "idle", ...(interrupted ? { interrupted: true } : {}) }) + } + async function stream(c: Channel, service: Api) { try { for await (const item of service.event.subscribe({ signal: c.abort.signal })) { @@ -344,6 +350,7 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { rpc: currentRpc, abort: new AbortController(), tools: new Map(), + busy: false, model: (session as { model?: ModelRef }).model, } try { @@ -382,9 +389,7 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { entries: (known ? sessions : [session, ...sessions]).map(conversationEntry), }) if (result.replaced) event(c, "notice", { message: "Conversation moved from another host to this one." }) - event(c, "status", { - state: (active as Record)[c.sessionID]?.type === "running" ? "busy" : "idle", - }) + status(c, (active as Record)[c.sessionID]?.type === "running") void stream(c, service) } catch (error) { await close(c) @@ -433,7 +438,14 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { if (targets.get(target.id) !== target) return const c = channels.get(target.id) if (c && !(await attached(c).catch(() => false))) await reconnect(target, c) - else await reconcile(target) + else { + if (c?.busy) { + const active = await (await api()).session.active().catch(() => undefined) + if (active && (active as Record)[c.sessionID]?.type !== "running" && c.busy) + status(c, false) + } + await reconcile(target) + } }) }, ms) target.retry.unref?.() @@ -535,7 +547,19 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { event(target, "notice", { message: "Queued messages were not sent to the new conversation." }) target.pending = [] } + const previous = target.params target.params = params + if ( + c && + previous && + !fresh && + !moved && + ["host", "port", "token", "registration", "script_handle"].every((key) => params[key] === previous[key]) + ) { + // A rename of the same live offer does not move the attachment or interrupt its stream. + deps.send({ id: request.id, result: {} }) + return + } if (fresh || moved) { target.selected = undefined target.fresh = fresh From cbcf373bf8fce9b86089c99220e116651b94b4d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:41:03 +0100 Subject: [PATCH 05/13] Assert a cold Godot offer waits without errors --- integrations/godot/test/godot.test.ts | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/integrations/godot/test/godot.test.ts b/integrations/godot/test/godot.test.ts index 5c9a24f..af651a7 100644 --- a/integrations/godot/test/godot.test.ts +++ b/integrations/godot/test/godot.test.ts @@ -228,18 +228,13 @@ describe("OpenCode Link in a real Godot editor", { skip: !godot, concurrency: fa await code( 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.reparent(EditorInterface.get_base_control())\ndock.show()', ) - const transcript = await until( - async () => { - const read = await code( - 'result.text = EditorInterface.get_base_control().find_child("OpenCode", true, false).transcript()', - { read_only: true }, - ) - return /Could not connect|Start OpenCode/.test(read.result.text) ? read.result.text : "" - }, - 30_000, - "the dock's answer", + await until(() => service.calls.some(({ method }) => method === "hosts"), 30_000, "the dock's offer lookup") + const read = await code( + 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.text = dock.transcript()\nresult.status = dock.state().status', + { read_only: true }, ) - assert.match(transcript, /Could not connect|Start OpenCode/) + assert.equal(read.result.status, "CONNECTING") + assert.equal(read.result.text, "") }) it("says that the editor crashed, with its log", async () => { From a504fc46b3b23eb4882a060559a1c1fb9eceadcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:44:08 +0100 Subject: [PATCH 06/13] Verify native runtime advertisements and deterministic host builds --- .../test/native-session-bindings.test.ts | 7 +++-- .../host/python/GafferOpenCodeUI/Client.py | 25 +++++++++++------- .../host/gaffer/opencode_link-0.3.0.zip | Bin 262923 -> 262942 bytes integrations/gaffer/plugin/package.json | 2 +- integrations/gaffer/test/python/real_host.py | 8 +++--- integrations/godot/test/godot.test.ts | 2 +- integrations/godot/test/helpers.ts | 7 ++++- .../houdini/plugin/scripts/build-host.ts | 2 ++ 8 files changed, 35 insertions(+), 18 deletions(-) diff --git a/integrations/blender/test/native-session-bindings.test.ts b/integrations/blender/test/native-session-bindings.test.ts index 81584be..91a8eb3 100644 --- a/integrations/blender/test/native-session-bindings.test.ts +++ b/integrations/blender/test/native-session-bindings.test.ts @@ -2,7 +2,7 @@ // Run after build with OPENCODE_TEST_BIN; this service has private config, state and credentials. import assert from "node:assert/strict" import { mkdirSync } from "node:fs" -import { join } from "node:path" +import { isAbsolute, join } from "node:path" import { it } from "node:test" import { startFakeHost } from "../../../packages/testing/src/index.ts" @@ -93,7 +93,9 @@ it("native exact-session binding: two Locations, move, delete, revocation and se assert.deepEqual(await read(a, "ses_native_missing"), { state: "unknown" }) const offer = announcement(host.endpoint, host.scriptHandle) - assert.deepEqual(await rpc(a, "advertise", offer), { outcome: "accepted" }) + const advertised = await rpc(a, "advertise", offer) + assert.equal(advertised.outcome, "accepted") + assert.ok(isAbsolute(advertised.panel_runtime)) const offerID = (await rpc(b, "hosts")).offers[0].offerID assert.deepEqual(await rpc(a, "attachHost", { offerID, sessionID: second.id }), { outcome: "refused" }) assert.deepEqual(await rpc(a, "attachHost", { offerID, sessionID: first.id }), { outcome: "attached" }) @@ -121,6 +123,7 @@ it("native exact-session binding: two Locations, move, delete, revocation and se const beforeLabel = await read(b, second.id) assert.deepEqual(await rpc(a, "advertise", { ...offer, label: "Blender: native renamed.blend" }), { + ...advertised, outcome: "renewed", }) const renamed = await read(b, second.id) diff --git a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py index e8ca9b9..7e48849 100644 --- a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py +++ b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py @@ -7,7 +7,6 @@ from Qt import QtCore from GafferOpenCode import panelServices -from GafferOpenCode.opencode_service import panel_launcher class ClientProcess : @@ -95,17 +94,19 @@ def __start( self ) : if not self.__targets or self.__process.state() != QtCore.QProcess.NotRunning : return + # Built into the installed part, beside the Python packages. + sidecar = pathlib.Path( __file__ ).resolve().parents[2] / "sidecar.cjs" + if not sidecar.is_file() : + self.__blocked( "OpenCode Link sidecar is missing; reinstall the application part." ) + return + from GafferOpenCode.opencode_service import panel_launcher + services = panelServices() waiting = time.monotonic() < self.__launchAt runtime, bun = panel_launcher( services, "NEURALNOMADS_GAFFER_NODE", wait = waiting ) - # Built into the installed part, beside the Python packages. - sidecar = pathlib.Path( __file__ ).resolve().parents[2] / "sidecar.cjs" - problem = ( "OpenCode Link sidecar is missing; reinstall the application part." if not sidecar.is_file() else - "No OpenCode runtime, NEURALNOMADS_GAFFER_NODE executable, or Node on PATH." if not runtime and not waiting else "" ) - if problem and problem != self.__problem : - self.__emitAll( "error", { "message" : problem } ) - self.__problem = problem - if problem or not runtime : + if not runtime : + if not waiting : + self.__blocked( "No OpenCode runtime, NEURALNOMADS_GAFFER_NODE executable, or Node on PATH." ) return environment = QtCore.QProcessEnvironment.systemEnvironment() environment.remove( "BUN_BE_BUN" ) @@ -117,6 +118,12 @@ def __start( self ) : self.__process.setWorkingDirectory( str( sidecar.parent.parent ) ) self.__process.start() + def __blocked( self, message ) : + + if message != self.__problem : + self.__problem = message + self.__emitAll( "error", { "message" : message } ) + def __started( self ) : pending = self.__pending diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index dd527fde6a5c8ab1dd51ca3067ab4a79545f486e..7badb6118a92f35618001c26daca4012ec5c8d00 100644 GIT binary patch delta 368 zcmeBf6PVW~(6EIu_9gG^B_7UGB^Ve$SaGtwg2eQumyG?}eO@sNa!+Uc#@MNonWm7J zU!qW)nUb2ESfrO(9G{k%ld7SqV8zAB$yuD5lcpCRpOllIoSm97eabgRH$F{}L{Vx< zX;B`KHC^x(qs{c_uZ+tqphgvy=9OgTra}yWij^m3mSpCoL&VTb)tJuuozag`bGyV3 z#yN};P`fk~Kz8dWZb-W ziB6yJmr-nbcPS%R`>LOeK+Lp#)lcSU?40m$nm&_}C4pI)iD|NTYD_Fz gjFYAZGO+|O{+qstiN%63X8LWQAlv$X%nS?+0F7XG4gdfE delta 333 zcmbQ&CeYm`(6EIu_9busq^ciH5)2F=tT@?TL1KE-OUC}`+TR#$whO&t6yTno`HgYO zbfvG1om>S)`AIpcxeB%l)31MJbeq2VE2E@PYEE$~7bm9z0!(-P&gkcunWm7JU!qV{ znpcvUo2rnQmjdROCuWvp=A|ouv?(YlDQE)q0+qsy1}THGr$_u`l%GEHFQbAhOtu!R zoU=GJCrvLt9wurF(}8MKei4cTthP`2&Nzp${rFE1X4-!IC-WV4PPq4{uVG|KU>0Cv un(U|`Ha(1qNo2Yu6N?sey*WgrhKa?3@%8krAj)(4JD?QXoPW#=3=9DLDRB`1 diff --git a/integrations/gaffer/plugin/package.json b/integrations/gaffer/plugin/package.json index e41c176..e414e7c 100644 --- a/integrations/gaffer/plugin/package.json +++ b/integrations/gaffer/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.3.0", "appVersions": ">=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "fa7eda277d9b229a43e53748fab09b64463ea1e55cb2ddc515ecf96438cb9165" + "sha256": "7c3ec47abbaa3cd1d4b48e76987a0ba3f491e9eb6dae928cfb37443c8cacdd10" } } } diff --git a/integrations/gaffer/test/python/real_host.py b/integrations/gaffer/test/python/real_host.py index 5cbed6f..9eae451 100644 --- a/integrations/gaffer/test/python/real_host.py +++ b/integrations/gaffer/test/python/real_host.py @@ -71,7 +71,7 @@ state.close() # --- the installed part as Gaffer's interface starts it, and the panel ------------------------------------------ -# Opening the panel does not start its sidecar nor touch the offers: Connect is the consent boundary. +# Opening the panel requests its own conversation immediately, without changing the script's offers. import GafferOpenCode from GafferOpenCodeUI.OpenCodeEditor import OpenCodeEditor root = Gaffer.ApplicationRoot("PrivatePanel") @@ -83,9 +83,9 @@ GafferOpenCode.initialise(types.SimpleNamespace(root=lambda: root), advertise=False) host = GafferOpenCode.currentHost() editor = OpenCodeEditor(script) -assert editor._OpenCodeEditor__channel is None -assert editor._OpenCodeEditor__client is None -assert editor._OpenCodeEditor__connectButton.getText() == "Connect" +assert editor._OpenCodeEditor__channel is not None +assert editor._OpenCodeEditor__client is not None +assert editor._OpenCodeEditor__conversationButton.getText() == "New conversation" print("GAFFER_PANEL_OK") # Each script is its own offer, labelled with its file (numbered when two scripts share it), under its own key. diff --git a/integrations/godot/test/godot.test.ts b/integrations/godot/test/godot.test.ts index af651a7..e69a579 100644 --- a/integrations/godot/test/godot.test.ts +++ b/integrations/godot/test/godot.test.ts @@ -233,7 +233,7 @@ describe("OpenCode Link in a real Godot editor", { skip: !godot, concurrency: fa 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.text = dock.transcript()\nresult.status = dock.state().status', { read_only: true }, ) - assert.equal(read.result.status, "CONNECTING") + assert.equal(read.result.status, "CONNECTING", read.result.text) assert.equal(read.result.text, "") }) diff --git a/integrations/godot/test/helpers.ts b/integrations/godot/test/helpers.ts index 838f274..696f96e 100644 --- a/integrations/godot/test/helpers.ts +++ b/integrations/godot/test/helpers.ts @@ -205,7 +205,12 @@ export async function fakeService(plugin: LoadedPlugin, root: string, loadedAt: const input = ((await body(request)) as { input?: unknown })?.input const directory = url.searchParams.get("location[directory]") calls.push({ method: match[1] ?? "", directory }) - if (!directory || !loadedAt(directory)) return send(400, { _tag: "RpcError", type: "rpc.unavailable" }) + if (!directory || !loadedAt(directory)) + return send(400, { + _tag: "RpcError", + type: "rpc.unavailable", + message: "RPC is unavailable: neuralnomads.godot", + }) return send(200, { output: await plugin.rpc(match[1] ?? "", input as object) }) } send(404, { type: "not_found" }) diff --git a/integrations/houdini/plugin/scripts/build-host.ts b/integrations/houdini/plugin/scripts/build-host.ts index ac585df..211489d 100644 --- a/integrations/houdini/plugin/scripts/build-host.ts +++ b/integrations/houdini/plugin/scripts/build-host.ts @@ -13,6 +13,8 @@ const manifest = JSON.parse(readFileSync(join(host, "manifest.json"), "utf8")) if (manifest.version !== pkg.version) throw new Error("Host and plugin versions differ") const check = process.argv.includes("--check") const bundle = await build({ + absWorkingDir: join(root, "..", "..", ".."), + preserveSymlinks: true, entryPoints: [join(root, "src", "sidecar.ts")], bundle: true, format: "cjs", From 6b7492d6b1f2f25bb65f8fe0e78dbcb9f9856103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:47:46 +0100 Subject: [PATCH 07/13] Show application tool names and simplify conversation selectors --- .../host/blender/opencode_link-0.4.8.zip | Bin 999776 -> 999976 bytes integrations/blender/plugin/package.json | 2 +- .../blender/test/console-chat.test.ts | 7 ++++++ .../host/gaffer/opencode_link-0.3.0.zip | Bin 262942 -> 263142 bytes integrations/gaffer/plugin/package.json | 2 +- .../godot/host/addons/opencode_link/dock.gd | 9 ++----- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 190576 -> 190510 bytes integrations/godot/plugin/package.json | 2 +- .../host/scripts/opencode_houdini/panel.py | 4 +-- .../host/houdini/opencode_link-0.3.1.zip | Bin 253844 -> 253931 bytes integrations/houdini/plugin/package.json | 2 +- integrations/houdini/test/panel_probe.py | 1 - packages/integration-kit/src/panel.ts | 23 +++++++++++------- packages/integration-kit/test/panel.test.ts | 4 +++ 14 files changed, 32 insertions(+), 24 deletions(-) diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 39a8306436abffb3e9e5e0dafe8b6076f772463f..1f5e31bd0f273a90d5e0826736a0493a7e2f04b1 100644 GIT binary patch delta 605 zcmaFRWV@opwxNZwg{g(Pg{6hHg{_6Xg`Z}SiP+L%sdSx z9R(##YoHxav-D$E|>~_r(o(+Qa z3TkQ!Ad~b`AYlVmT9%)gqF?|C8i+}#O29f`feDs^glI})Ng`H9plAn$F~l*cWz$94 zcr@9ec2D}g*Q)UcjUKV{50Lckza}}-H@Mw GfdK%n`N_%v delta 431 zcmZ3{V*8-UwxNZwg{g(Pg{6hHg{_6Xg`K}+Jlr0~&%Hg4 zpQkoXI5RIVwJ0P%Kc`qDGq0euL{p)9x=bFA%k)!cdAO!$#9*ZkW#_#;IVXP?n#WqF}JSDxYU3i+@34QHdT%nS!mYt%6c&MQUWw)d3qY!EaCx`;~w3P9pOO+Y6r*dm*m zl30=mHOv~Qc>2S39*OCv+jt~-A&Two6+l|2&u-;WoX+0Pvu*nGb{-p6uw=Vd2M-YQ zZrAGId%6QDl%`8M@_TY5T;^dYNi5Eu{?UYAWO|(=zZA!fpFp9E%)IFbjrfJ9r#ABm t@G!tZf7A5yj{FviS`z#W<(WmPdIgmM-mGjOc{?CnEx^Dq-+&*;0|3ruj^O|R diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index 6e9bab5..f37a69e 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.4.8", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "2f78c866745c5d2bd21ede4e78fc9c1a1f14976db9fd1d68f8c0e52d25ca72ec" + "sha256": "bcc6653efdd8669b6e713b0fcf95c49521945aac270e97e8b3f22bf00753158f" } } } diff --git a/integrations/blender/test/console-chat.test.ts b/integrations/blender/test/console-chat.test.ts index 0921644..e54a569 100644 --- a/integrations/blender/test/console-chat.test.ts +++ b/integrations/blender/test/console-chat.test.ts @@ -101,6 +101,9 @@ it("the sidecar resumes a folder conversation and streams wrapped tool names and await emit("session.text.delta", { delta: "hello\n" }) await emit("session.tool.input.started", { id: "tool_1", name: "blender_context" }) await emit("session.tool.success", { id: "tool_1" }) + await emit("session.tool.input.started", { id: "lookup", name: "execute" }) + await emit("session.tool.called", { id: "lookup", input: { code: 'return search({ namespace: "blender" })' } }) + await emit("session.tool.success", { id: "lookup" }) await emit("session.tool.input.started", { id: "tool_2", name: "execute" }) await emit("session.tool.called", { id: "tool_2", input: { code: "await tools.blender.context({})" } }) await emit("session.tool.success", { id: "tool_2" }) @@ -118,6 +121,10 @@ it("the sidecar resumes a folder conversation and streams wrapped tool names and assert.ok(completed.data.duration_ms >= 0) assert.equal((out[5] as typeof completed).data.name, "blender_context") assert.equal((out[6] as typeof completed).data.name, "blender_context") + assert.equal( + out.some((item) => JSON.stringify(item).includes('"name":"execute"')), + false, + ) assert.deepEqual(out.at(-1), event("status", { state: "idle", interrupted: true })) assert.deepEqual(calls, [ { sessionID: session.id, text: "hello" }, diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index 7badb6118a92f35618001c26daca4012ec5c8d00..17e70ce18b76226750b1f35a15df2feacdc87528 100644 GIT binary patch delta 542 zcmbQ&Ch)9XprM6v3lon8r&`3$tA7tOGW=~9wP4yVYQbC==U9@TpW~8QT#%DksgakM zo2sLbnO9I+qNz~LrJ#_RrT`XHP_(sGP)e;xO)f1-Rnk-_N-ZfZ%2NQTx1PRi8nX)v zh&lbkH0JH`Fg?Y3#hF#9aJA8TdU_y5#j$!>`I&hdN;(Qkn$|!&pl0dEBo(J77A0rI z6l=w3=If9=pfH9wCbew(nRU#X>`=R>v#)2qqy%y_NWDFZ tlaO6M{o;CN7nr8)QX7~Xf)G(YeK8Y@7n91L>F=3XG}+4kGczzS008o|xNraf delta 317 zcmaFXE-461e^|JCa z^E8xn6sDhVXO`G*KZAJ<3rj&_QOWd&>zKt&kjw`O>J^tHmZaM2LG7xkQ2>jAj8Xt{ zluCduQQGb@mwAJr3eYKB3QzzN2WkSkRl!yP$;|1F>zPHT7p`a4=7q@G+be+7P7hwk ztT=uDdgg7@cb#G8n!a)avk@y;#r8)Vm>Yr+VKF_MnZ=7a<~Q?n$3M&x(=RZy2(YdH J$IQUM001Y8Z$JP5 diff --git a/integrations/gaffer/plugin/package.json b/integrations/gaffer/plugin/package.json index e414e7c..8271ef9 100644 --- a/integrations/gaffer/plugin/package.json +++ b/integrations/gaffer/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.3.0", "appVersions": ">=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "7c3ec47abbaa3cd1d4b48e76987a0ba3f491e9eb6dae928cfb37443c8cacdd10" + "sha256": "c20791f784340ffbdab15963d1a524825ad4340e39ce4eba656a61e0c6ce71f7" } } } diff --git a/integrations/godot/host/addons/opencode_link/dock.gd b/integrations/godot/host/addons/opencode_link/dock.gd index 4d3a66c..7571e25 100644 --- a/integrations/godot/host/addons/opencode_link/dock.gd +++ b/integrations/godot/host/addons/opencode_link/dock.gd @@ -26,7 +26,6 @@ var _permission := "" var _models: Array = [] var _model := "" -var _session_label := Label.new() var _status_label := Label.new() var _agent_label := Label.new() var _model_button := OptionButton.new() @@ -45,10 +44,7 @@ func _ready() -> void: var brand := Label.new() brand.text = "OpenCode" header.add_child(brand) - _session_label.text = "" - _session_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL - _session_label.clip_text = true - header.add_child(_session_label) + header.add_spacer(false) _status_label.text = "CONNECTING" header.add_child(_status_label) add_child(header) @@ -337,8 +333,7 @@ func _event(name: String, data: Dictionary) -> void: _connected = true _selected = str(data.id) if data.get("id") else "" _draft = data.get("draft", false) - _session_label.text = "Session " + _selected.right(8) if _selected != "" else "New conversation" - _session_label.tooltip_text = "Workspace: " + str(data.get("workspace", "")) + _conversations.tooltip_text = "Workspace: " + str(data.get("workspace", "")) _agent_label.text = str(data.get("agent", "")) if data.get("agent") else "default agent" _set_model(str(data.get("model", ""))) "conversations": diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index 2c2bccf7e448442be28c04f1c646c47a66b3fc3e..4080eaa7a78a13cbde70d9f8fbc26905c18628bf 100644 GIT binary patch delta 718 zcmZuv&ubGw6y7|7fo*A8)QYJ1x=PKKFtrpbG=w08f_m^?6T_ID(v@{L-I>H+ht^*5 z2Lv5jFW!Yv47hspQ1B!ad+_AZq~gUNcsH}#tqC|VF!SE`zW2Rv=EvShdv9c?k<@p; ze1FdtG>t8EHj;m!BU4x4^eUqk^9i-A3a`;B^D`^d;mp)q=dVt7*7Xk;T1#_dowsE3 z_t?i*>DTGqgr+uXa;*!eniV4vR1A1<=bG?5r)cwadY@&{c58KE;u9UwUcoSk zQ~5j^>>;bx1v54EqIVH{o4!bWpaOXu|QuEY_$m z2p3ea0*QuD{LzY4VZJ|!qWdST99(R|&cr%SPottGR%AyAZFshYmm@bKreR1}5&IXW zA`>kt=zm2Fl`C5#F{~leTVSRRd&?VJ@X1i36}~VeX;8g9u?@wzC@613`{uxhkte&b z45^%Y^Xss*9KOBW@4_7HKMOCdajDBoJ(z*^^Ei-_Ydy%q=NA$DO%LV)e@5BzFI|ov d!1%f0Po)hkV=5tE_Fz)pI)F3BysyyD{RNLa@QnZf delta 725 zcmY*X&ubG=5Y7&%nuJJ$pkgUbR;WpB7p-VT8}=d=6jabtOWi)Rqgh>d!|qEgwqm^K z#fvQRstEoCmP)`VUKIagcSJ$I}qHUFp z9*TPvN+wFgO!72lnntl?*=8;(S^tvwdE`-4q~GOQw>PSI3?<8^A}3SxtlK4?JCjH2 z)=n0)p(`ZYCsZ%feJr|8l{}wuX#y-n&$h$6ye$H~r6`sdsk*>jcVU}T77&Ul1J% zAk=YQ)3i=vLA&ExPEMUbHIHYp>RKiqZ`^$hALCcb%;Oyt77B6{TB2fwlZs=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "36466e243f345ab9803f1e6c82d4e734fead8e1f462a47d965e53b0b57de40c3" + "sha256": "d2954d05ae504c34702149aadac07cae2ea2040572532d8dd5725f97b454adf4" } } } diff --git a/integrations/houdini/host/scripts/opencode_houdini/panel.py b/integrations/houdini/host/scripts/opencode_houdini/panel.py index 9dcd4f1..695ebc7 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/panel.py +++ b/integrations/houdini/host/scripts/opencode_houdini/panel.py @@ -216,13 +216,12 @@ def _build_ui(self) -> None: header = QtWidgets.QHBoxLayout() brand = QtWidgets.QLabel("OPENCODE / HOUDINI") brand.setObjectName("openCodeHoudiniBrand") - self._session = QtWidgets.QLabel("SESSION connecting") self._status = QtWidgets.QLabel("STARTING") self._status.setObjectName("openCodeHoudiniStatus") self._conversations = Conversations() + self._conversations.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToContents) self._conversations.addItem("New conversation", None) header.addWidget(brand) - header.addWidget(self._session) header.addStretch(1) header.addWidget(self._status) header.addWidget(self._conversations) @@ -332,7 +331,6 @@ def _event(self, channel: str, name: str, data: dict) -> None: return if name == "session": self._connected = True - self._session.setText("SESSION " + str(data["id"])[-8:] if data.get("id") else "New conversation") self._append("system", "Resumed session" if data.get("resumed") else "New session") elif name == "history": self._transcript.clear() diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip index 93ed70cf5ae644851aaa7a56c461530d54302dd9..607fc6216ed4f44fa46fea61644db3f13e9482fa 100644 GIT binary patch delta 691 zcmbQTpa1oK{)R1#m8*DF;+vahdNVM9u;S$NB{JI=tz!JAH2uL@#?_w1sU^XgRjH0C zS*67#0r@$Z$(0&`CE=MV>8T~fdV$XQxk>p>`4xKTiu52lLh_yS^GZ_lN{Xj1yv8U$ zz2_Wb@OJj|jOPTW3p{0H+wT34G2fiaCN!OE(_u!2O^4f$NHA?bBEei6r&yAopW~8Q zT#%DksgakMo2sLbnO9I+qNz~LrJ#_Rrl2uBp^sUFrzo|gv?xyjq{4c7NIA0$3y3*= zUODsjc#tX(uUM}b=m$*&sM=^fJw32+tX@`rW}b$Uj)Ib=HPBS3ynaklacW{waz;$C zR*Z(eUP)?kiAHjM3eW_5g}l<790e<|ecRhBn0K@KpkQljt5BAonWA6- z@jpZ}suHjcScrk8K%Uf5NJ%V7#A+{!c155KAirrUq?S#u>SxwuhuS@TYd`ZPC6GHo z>g`dS1knHqw(0c~m|b9+wx5{5yv&yik+h~)++&VscK*gV{o*%9<>`O#F>5ilPuIB5 btSgO(eMSau24rA8z2H8x9Glo3W}qkl@pC^kpGVYxo|AjP0M!F+LKEf%5c@G_!Do!i`x>9Mnp(~@v^!ZO1*|y($z?g5& zwJjsi_|+jshF6E$gC&@@2TL&5#tCNvU0W2ApPy5#k(pOeTB4~?JzcPz*=0J{WoEAF zvE|I0)r(R~N{jLo@)C1Xi}i{#t5Oy06{7X@^uPkKdRh6Ic^XPO3e$Nqm?gH?R4}h$ zVJS!~Dw!_V&n#|&WIjkxuec+nJp+uJLEv`(MU$E-O0Pe1dv>31eD+pvNq zx64mtUgpb%i1F#??=iE8F5jTwJTufNZ%D~$*`Mh0#MWUyxX@%zkj KZ2NCB14RM2=21.0", "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "2d932d8ea342e27be90e6af1cd0abd3bccf672f4da7aa8c58f7db030c89a1b57" + "sha256": "50f5812b1c8552aeadcc76501e33eebaa3d04c6db2b2906a15fb6bef89617597" } } } diff --git a/integrations/houdini/test/panel_probe.py b/integrations/houdini/test/panel_probe.py index 81ecbaa..ed1870d 100644 --- a/integrations/houdini/test/panel_probe.py +++ b/integrations/houdini/test/panel_probe.py @@ -105,7 +105,6 @@ def test_shared_host_lifetime(self): widget._status = Mock() widget._send = Mock() widget._prompt = Mock() - widget._session = Mock() widget._append = Mock() widget._target = None integration.acquirePanel(widget._channel) diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts index 4fed2d5..90b2c52 100644 --- a/packages/integration-kit/src/panel.ts +++ b/packages/integration-kit/src/panel.ts @@ -23,7 +23,7 @@ type Channel = { handle: string rpc: Rpc abort: AbortController - tools: Map + tools: Map busy: boolean model?: ModelRef } @@ -62,16 +62,19 @@ export type PanelDependencies = { class PanelError extends Error {} class WaitingForOffer extends Error {} -function innerTools(input: unknown) { +function toolDisplay(name: string, input: unknown) { + if (name !== "execute") return name const code = (input as { code?: unknown } | null)?.code - if (typeof code !== "string") return undefined + if (typeof code !== "string") return name const names = new Set( Array.from( code.matchAll(/\btools\.(\w+)(?:\.(\w+)|\[['"]([\w-]+)['"]\])\s*\(/g), ([, ns, dot, key]) => `${ns}_${dot ?? key}`, ), ) - return names.size ? [...names].join(", ") : undefined + if (names.size) return [...names].join(", ") + // Code Mode discovery is a separate execute call, not an application tool invocation. + return /\bsearch\s*\(/.test(code) ? null : name } // An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. @@ -118,7 +121,8 @@ function history(messages: ReadonlyArray) { return (message.content ?? []).flatMap((part) => { if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] if (part.type === "tool") { - const name = (part.name === "execute" && innerTools(part.state?.input)) || part.name || "tool" + const name = toolDisplay(part.name || "tool", part.state?.input) + if (name === null) return [] return [{ role: "tool", text: `${name} / ${part.state?.status ?? "unknown"}` }] } return [] @@ -238,16 +242,17 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { if (data.name !== "execute") event(c, "tool", { id: data.id, name: data.name, state: "starting" }) } else if (type === "session.tool.called") { const tool = c.tools.get(String(data.id)) - if (tool?.name === "execute") { - tool.inner = innerTools(data.input) - event(c, "tool", { id: data.id, name: tool.inner ?? tool.name, state: "starting" }) + if (tool?.name === "execute" && tool.display === undefined) { + tool.display = toolDisplay(tool.name, data.input) + if (tool.display !== null) event(c, "tool", { id: data.id, name: tool.display, state: "starting" }) } } else if (type === "session.tool.success" || type === "session.tool.failed") { const tool = c.tools.get(String(data.id)) c.tools.delete(String(data.id)) + if (tool?.display === null) return event(c, "tool", { id: data.id, - name: tool?.inner ?? tool?.name, + name: tool?.display ?? tool?.name, state: type === "session.tool.success" ? "completed" : "failed", ...(config.consoleEvents && tool ? { duration_ms: Math.round(performance.now() - tool.started) } : {}), }) diff --git a/packages/integration-kit/test/panel.test.ts b/packages/integration-kit/test/panel.test.ts index dfd37a8..20622b1 100644 --- a/packages/integration-kit/test/panel.test.ts +++ b/packages/integration-kit/test/panel.test.ts @@ -111,6 +111,10 @@ it("queues during startup, starts drafts lazily and selects/rebinds folder conve await until(() => prompt.length === 1) assert.equal(sessions[0]?.title, "Test: shot") assert.deepEqual(prompt[0], { sessionID: "created-0", text: "early" }) + assert.deepEqual( + out.filter(({ event }) => event === "user_message").map(({ data }) => data.text), + ["early"], + ) sessions.push( { id: "codenomad", title: "CodeNomad", location: { directory }, time: { updated: 200 } }, From c94117c444d5c2c6c45b0d8b3357b82a26253164 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:51:55 +0100 Subject: [PATCH 08/13] Let OpenCode title new in-app conversations --- .../host/opencode_link/_console_opencode.py | 6 +++-- .../host/blender/opencode_link-0.4.8.zip | Bin 999976 -> 1000328 bytes integrations/blender/plugin/package.json | 2 +- .../host/gaffer/opencode_link-0.3.0.zip | Bin 263142 -> 263352 bytes integrations/gaffer/plugin/package.json | 2 +- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 190510 -> 190720 bytes integrations/godot/plugin/package.json | 2 +- .../host/houdini/opencode_link-0.3.1.zip | Bin 253931 -> 254141 bytes integrations/houdini/plugin/package.json | 2 +- packages/integration-kit/src/panel.ts | 11 ++++++--- packages/integration-kit/test/panel.test.ts | 23 +++++++++++++----- 11 files changed, 33 insertions(+), 15 deletions(-) diff --git a/integrations/blender/host/opencode_link/_console_opencode.py b/integrations/blender/host/opencode_link/_console_opencode.py index f714f46..c6f702c 100644 --- a/integrations/blender/host/opencode_link/_console_opencode.py +++ b/integrations/blender/host/opencode_link/_console_opencode.py @@ -198,7 +198,7 @@ def output(text="", end=False): self.problem = "" if self.selected: append("INFO", "Resumed conversation." if data.get("resumed") else "New conversation attached.") - append("INFO", self.status()) + append("INFO", self.status()) elif name == "conversations": self.entries = data["entries"] self.redraw = True @@ -386,7 +386,8 @@ def banner(context): chat.active = True _sync(_append) context.space_data.prompt = "> " - _append("INFO", chat.status()) + if chat.state != "Ready" or chat.selected: + _append("INFO", chat.status()) _append("INFO", HELP) return {"FINISHED"} @@ -402,6 +403,7 @@ def _menu_classes(): class OPENCODE_OT_console_conversation(bpy.types.Operator): bl_idname = "opencode.console_conversation" bl_label = "Open conversation" + bl_description = "Switch to a conversation in this folder, or start a new one" session_id: bpy.props.StringProperty() def execute(self, _context): diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 1f5e31bd0f273a90d5e0826736a0493a7e2f04b1..d4c5cfca1d9c5d8cd8e591ad3b04c6e8ae868aa1 100644 GIT binary patch delta 1251 zcmY*YT}&KR6rPz~x)&IFme57nVi*=BEUjC*3%grje}Ee8pKZ1wJ~YrycL!O!ox$A! zx>ig~n?MBG8Y0KGp`@WwW7F1_MhwxW5{a=Yy!aEV4;mkQY1(4cm}t~9I}PGYzT7$A zJ>PflnRD;k$3sJdp?9AfF1R)F`JLi6jw^1Pk%z~fW9kKQY|ljLjAQy{xjWe<#k*zQ zlhI{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mkxIjc!=3`nsFp*(#QXMKViP99?dj^s#bQ&sU_MB#BeU z6tl5`Ek(&g=ByCIu@K9SF)em`K+iA3K@X*UB!a&@U=>0mXpyLXc#j7qFbhxO@U}!z za5yPZdLl0Mf`d;-*$Yl#v>UH@!J>*r)L7fEPQfo;+U-Kr`M|< |*TPWyNEd2U`H z^vT!bX&+cw_A3n+ln+%ZxxMp&o?ZP(5@o3z&ghAx`4N@2qH!%)Gr#MAJ4!!8UTuBx TmiPs+4Bd3y)pFea)j;eoE^;;N diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index f37a69e..7a4ff08 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.4.8", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "bcc6653efdd8669b6e713b0fcf95c49521945aac270e97e8b3f22bf00753158f" + "sha256": "311d693ba77b98dcd1f27a16874bde52ccd169e91a4ad80aa39abc9fc42d1bfe" } } } diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index 17e70ce18b76226750b1f35a15df2feacdc87528..8c878630435c06a596b76929bc15b91cb06a5053 100644 GIT binary patch delta 259 zcmaFXF0i9hprM6v3lon8*YB23O6QL-GMqosE@r{BUCe^{eXXCOt*t_`UU6!1ab|v= zr;DaSa(-S(W?pHkHJ1VuWTq)-WR|4n>XlR$q$=0~H7G&V>lLNuCFZ84C}}EGgOyJ& z+Qw`+J?<8>{PZ{5nE8c3CV;e;Bo?KomMEyHDNN^E$t*Q}$8BbL#^mXB_nF0YYc=(f z6HAgaG&D37Z0(>1L9DLTM7W|>AvLEsb-U;`=2Fh>Pxmv|IwN^#dJZ#-C-b*I%+nqJ TFiT9oz|11R=E=aqz`y_iR~k}! delta 162 zcmdndDe$aaprM6v3lon8ms-TmtA7tOGW=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "c20791f784340ffbdab15963d1a524825ad4340e39ce4eba656a61e0c6ce71f7" + "sha256": "bc7cc5e2a75ed4f9ab981bc6bdec3939ee3ffe95ef03b19ca2267dc5f7f5103a" } } } diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index 4080eaa7a78a13cbde70d9f8fbc26905c18628bf..563a6173d36d3390b8a0076bd824b129ad1e0abc 100644 GIT binary patch delta 274 zcmZ2?fxF=ncf%G&14Z7YoU%I~9${nvVTH+wQ4-U6UodgECnz#*Pf%pKSL>%}Ypal~ zSDad0oSC2J>7uESoS#>cnOB->&7}YZnQ00dnI);YdL@+wsS3704N6e;dPS*uiMgpM zN}3AQVCBlRVAd;+?l3A3RT#{c@sR^@wde06fNePHcYT=>^3bhJAb5gha&1Wj* goPMQ)Np!pMN~Yy@oNy0MfBc-umCf-P69WSS0LJ@QQ2+n{ delta 163 zcmZp;#J%nUcf%G&14Z7mtNAzaA7NwwVTH+wQ4-VdzhL5SPf%pso}kEduXg&GNlg5V zn%k=vFqLvjmSmRXq*^H?s8lEC=cQ$)>m?Qx)LJR1R8Mc5z$B`flvtdamzbNXsgaUd zl$u_gu7t+))!2!Z23=_7#J7;o)9>} diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json index 08eda18..aab89ad 100644 --- a/integrations/godot/plugin/package.json +++ b/integrations/godot/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.1.0", "appVersions": ">=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "d2954d05ae504c34702149aadac07cae2ea2040572532d8dd5725f97b454adf4" + "sha256": "2f20561a8949d8a3fec63e65a2866f7df5792559d09a00ce6e1544325b7dfe7f" } } } diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip index 607fc6216ed4f44fa46fea61644db3f13e9482fa..395d399719251ab65a6eb1a0877a0b050472e44d 100644 GIT binary patch delta 245 zcmaF8pMUQ`{)QIDEli#gTw*Z{-7QBL8Cs6C2TL$*50+qlU+br6Ypal~SDad0oSC2J z>7uESoS#>cnOB->&7}YZnQ00dnI);YdL@+wsS3704N6e;dPS*uiMgpMN}3AQVCB;t zH!zD%KQfJ3X8P=1%<|JUr!(_U?{Q(`;3`QhN>43OP*YQw?%l~OHT~;uW_gihy_C$N z)Z~)IvGHg2B9xTDMJy?SIeXW44t*t_`UU6!1ab|v= zr;FzH`svK2oRTG(B{`{93JEIJ$@zI{ndy3o1qHQM3M$ppKVD`QQPoRIEKbc!%uUtQ tNXaZpO)kkVs?=1dsZoIQY7=y}zh1yR*&fN-=^YQ4_1VPkFf%YP001oEH|_uc diff --git a/integrations/houdini/plugin/package.json b/integrations/houdini/plugin/package.json index 2ab1a62..af3d968 100644 --- a/integrations/houdini/plugin/package.json +++ b/integrations/houdini/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.3.1", "appVersions": ">=21.0", "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "50f5812b1c8552aeadcc76501e33eebaa3d04c6db2b2906a15fb6bef89617597" + "sha256": "e77903d8cd907e92fceac47bf7d707cd610706210762a6e34663dca9c3e16538" } } } diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts index 90b2c52..ff4c57d 100644 --- a/packages/integration-kit/src/panel.ts +++ b/packages/integration-kit/src/panel.ts @@ -1,6 +1,6 @@ // An in-app chat is a plain client: attach its conversation to the host's existing offer, never announce one. -import { basename, normalize } from "node:path" +import { normalize } from "node:path" import type { OpenCode } from "@opencode/client" import { rpcDefinition } from "./contract.ts" import { requestHost as kitRequestHost } from "./host-client.ts" @@ -277,7 +277,13 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { try { for await (const item of service.event.subscribe({ signal: c.abort.signal })) { const data = item.data as unknown as EventData - if (data?.sessionID === c.sessionID) forward(c, item.type, data) + if (data?.sessionID !== c.sessionID) continue + if (item.type === "session.renamed") { + void serialize(c.id, async () => { + const target = targets.get(c.id) + if (target && channels.get(c.id) === c) await conversationList(target, c.directory) + }).catch(() => {}) // Opening the selector refreshes the list again. + } else forward(c, item.type, data) } } catch { // ended below @@ -337,7 +343,6 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { known ?? (await step(`creating this ${config.document}'s conversation`, () => service.session.create({ - title: `${config.app}: ${basename(directory) || directory}`, location: { directory }, }), )) diff --git a/packages/integration-kit/test/panel.test.ts b/packages/integration-kit/test/panel.test.ts index 20622b1..17bfc32 100644 --- a/packages/integration-kit/test/panel.test.ts +++ b/packages/integration-kit/test/panel.test.ts @@ -54,8 +54,14 @@ it("queues during startup, starts drafts lazily and selects/rebinds folder conve }), session: { list: async () => ({ data: sessions, cursor: {} }), - create: async ({ title, location }: { title: string; location: { directory: string } }) => { - const item = { id: `created-${sessions.length}`, title, location, time: { updated: 100 } } + create: async (input: { location: { directory: string } }) => { + assert.deepEqual(input, { location: { directory } }) + const item = { + id: `created-${sessions.length}`, + title: "OpenCode default", + location: input.location, + time: { updated: 100 }, + } sessions.push(item) return item }, @@ -109,7 +115,7 @@ it("queues during startup, starts drafts lazily and selects/rebinds folder conve assert.equal(prompt.length, 0) label = "v001" await until(() => prompt.length === 1) - assert.equal(sessions[0]?.title, "Test: shot") + assert.equal(sessions[0]?.title, "OpenCode default") assert.deepEqual(prompt[0], { sessionID: "created-0", text: "early" }) assert.deepEqual( out.filter(({ event }) => event === "user_message").map(({ data }) => data.text), @@ -124,13 +130,18 @@ it("queues during startup, starts drafts lazily and selects/rebinds folder conve label = "v002" await call("connect", params(label)) assert.equal(current(), "created-0") + const first = sessions[0] + assert.ok(first) + first.title = "Generated from the first message" await call("list") + const entries = out.findLast((item) => item.event === "conversations")?.data.entries as + | { id: string; title: string }[] + | undefined assert.deepEqual( - ((out.findLast((item) => item.event === "conversations")?.data.entries ?? []) as { id: string }[]).map( - ({ id }) => id, - ), + entries?.map(({ id }) => id), ["codenomad", "created-0"], ) + assert.match(entries?.[1]?.title ?? "", /^Generated from the first message \(.+ ago\)$/) attached.set("codenomad", "other-host") await call("open", { session_id: "codenomad" }) assert.equal(current(), "codenomad") From 67f55a95dc243db491a7dbab3e716f7fb9311031 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:53:16 +0100 Subject: [PATCH 09/13] Print the Blender connection banner only once --- .../host/opencode_link/_console_opencode.py | 2 -- .../host/blender/opencode_link-0.4.8.zip | Bin 1000328 -> 1000242 bytes integrations/blender/plugin/package.json | 2 +- .../blender/test/console_chat_test.py | 13 +++++++++++++ 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/integrations/blender/host/opencode_link/_console_opencode.py b/integrations/blender/host/opencode_link/_console_opencode.py index c6f702c..7b26cd3 100644 --- a/integrations/blender/host/opencode_link/_console_opencode.py +++ b/integrations/blender/host/opencode_link/_console_opencode.py @@ -386,8 +386,6 @@ def banner(context): chat.active = True _sync(_append) context.space_data.prompt = "> " - if chat.state != "Ready" or chat.selected: - _append("INFO", chat.status()) _append("INFO", HELP) return {"FINISHED"} diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index d4c5cfca1d9c5d8cd8e591ad3b04c6e8ae868aa1..16eb58ba2c491b29289b839bbb13d642c5863bd9 100644 GIT binary patch delta 810 zcmY+CT}TvB6vt;~cb)5MdxkV<*U(I~Fi>#Uof+5Nof!*>AlI;ZsKhCwmP|L>@`LDu zN<$$ji4zeOh!sUrCWLE+wniYbJyZ|%5Isg9^iTIrkx4j-EFzm& z@l;Q`?6GA+TCvavIr!WQ9$|I?KX^gq4b1UDfM1JsJ}~%tyy7EM z!&x85;?I=8?Qd(xsQ~0+ekFMLm8e#NF3b+$$w~+b<8FMG)?*v-FKPY;hWsQ)8}Y0k zs`&`M@I$TeHXlV9!c?_ZrZa}IPlg)dT{pgwDQ6g63T?)5n*tgw0}7cErpOe2#1T~3 z#CKwYN}KEPstN}C9u>Jm(bhQD`{`cO4@D`9TY8$%RRw#6&M|~4ScA83F*hEm1_|#b zL@9eIjH^jl0bi?Ni_r1X5{{&}%8HK8{8!b1mjlp97x)%{oos4eu?!t$`rWI0yC^$-=xYgzQYmi3D)ab1^{T;9!!Q43S@?g56W0k$EnBpeRYL5(;W zhJY|KjtgN>gx51DYoPFMjA`H(=IwY-qyMkq7mZpL#$uhup#e>ulml<-px741ofu0v zb8$|mPu+~G4UqXW7%^y6PGO$`3afaZ&Be`QhpnD`GQh*`|0aw2WDVV`^RDG>GO?@% g)WSb*;5wr12g+hyk*$u5bbCVdK9D%>Xa$h^2W`Rgi2wiq delta 880 zcmYk4Ye-XJ7{||Tp3^j+$xLe&*@z+ygLZM#ZD*T(h%yMn`e3L_kGPo5wrN@Up~4ij z859;=*7}wq|^nH#?M zj7Zq1fd7eaOcazF6xzupULTauG$`ev)6T4GmgByiRK6dRc9voW)?z9X3l8WoxnF0* zv0~O>22YAf6-VFeaO%A-8<`F!j>73658r@&4pN29tr&FB27U~)4)XFHP@UwLH|>_W z#$Yps?X(CNoMaLo-Ih@sm-F!bf|7&s5;9;WsgDiJ>-PraB}u(NJR6^rN>WvwBeEg= z-!X76@v($K@~*pPVZyOvLRCMzo@q_N|+B SX~~23u=kdM=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "311d693ba77b98dcd1f27a16874bde52ccd169e91a4ad80aa39abc9fc42d1bfe" + "sha256": "a99bdb0e685bfad38b28db41ec8f00cb0c35ec793af1f551828235ac47f2accb" } } } diff --git a/integrations/blender/test/console_chat_test.py b/integrations/blender/test/console_chat_test.py index 32d9df0..12e9cc0 100644 --- a/integrations/blender/test/console_chat_test.py +++ b/integrations/blender/test/console_chat_test.py @@ -13,6 +13,19 @@ class ConsoleTests(unittest.TestCase): + def test_banner_reports_ready_once_with_model(self): + console.bpy.data = NS(filepath="/project/shot.blend") + chat = console.Chat() + rows = [] + append = lambda kind, text: rows.append((kind, text)) + chat._event({"event": "session", "data": {"id": None}}, append) + self.assertEqual(rows, []) + chat._event({"event": "session", "data": {"id": "ses_shot", "model": "provider/model"}}, append) + self.assertEqual(rows, [ + ("INFO", "New conversation attached."), + ("INFO", "OpenCode | shot.blend | Ready | agent: default | model: provider/model"), + ]) + def test_lines(self): lines = console.Lines() self.assertEqual(lines.feed("## Heading\r\n**hel"), ["Heading"]) From 9ecf680002e125bad3cb8a256fb57032240f251e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:58:00 +0100 Subject: [PATCH 10/13] Restore recent history when opening an in-app conversation --- .../host/opencode_link/_console_opencode.py | 33 ++++++++++++--- .../host/blender/opencode_link-0.4.8.zip | Bin 1000242 -> 1001297 bytes integrations/blender/plugin/package.json | 2 +- .../blender/test/console-chat.test.ts | 39 +++++++++++++++++- .../blender/test/console_chat_test.py | 19 +++++++++ .../python/GafferOpenCodeUI/OpenCodeEditor.py | 1 + .../host/gaffer/opencode_link-0.3.0.zip | Bin 263352 -> 263773 bytes integrations/gaffer/plugin/package.json | 2 +- .../godot/host/addons/opencode_link/dock.gd | 1 + .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 190720 -> 191135 bytes integrations/godot/plugin/package.json | 2 +- .../host/scripts/opencode_houdini/panel.py | 1 + .../host/houdini/opencode_link-0.3.1.zip | Bin 254141 -> 254570 bytes integrations/houdini/plugin/package.json | 2 +- packages/integration-kit/src/panel.ts | 20 +++++---- 15 files changed, 104 insertions(+), 18 deletions(-) diff --git a/integrations/blender/host/opencode_link/_console_opencode.py b/integrations/blender/host/opencode_link/_console_opencode.py index 7b26cd3..94ee6b4 100644 --- a/integrations/blender/host/opencode_link/_console_opencode.py +++ b/integrations/blender/host/opencode_link/_console_opencode.py @@ -176,6 +176,15 @@ def output(text="", end=False): for line in self.lines.feed(text, end): append("OUTPUT", line) + def user(text): + for line in text.splitlines(): + append("INPUT", "> " + line) + + def tool(data): + elapsed = data.get("duration_ms") + duration = "" if elapsed is None else f" ({elapsed / 1000:.2f} s)" + append("INFO", f"Tool: {data.get('name') or 'tool'} — {data['state']}{duration}") + if name == "exit": output(end=True) self.pipes = None @@ -190,8 +199,6 @@ def output(text="", end=False): elif name == "notice": append("INFO", data["message"]) elif name == "session": - if data.get("draft") and not self.draft: - append("CLEAR", "") self.selected = data["id"] self.draft = data.get("draft", False) self.state, self.agent, self.model = "Ready", data.get("agent"), data.get("model") @@ -199,6 +206,21 @@ def output(text="", end=False): if self.selected: append("INFO", "Resumed conversation." if data.get("resumed") else "New conversation attached.") append("INFO", self.status()) + elif name == "history": + self.lines = Lines() + append("CLEAR", "") + for message in data["messages"]: + role, text = message["role"], message["text"] + if role == "user": + user(text) + elif role == "assistant": + output(text, end=True) + elif role == "tool": + tool(message) + else: + append("INFO", text) + elif name == "user_message": + user(data["text"]) elif name == "conversations": self.entries = data["entries"] self.redraw = True @@ -215,9 +237,7 @@ def output(text="", end=False): elif name == "assistant_end": output(end=True) elif name == "tool": - elapsed = data.get("duration_ms") - duration = "" if elapsed is None else f" ({elapsed / 1000:.2f} s)" - append("INFO", f"Tool: {data.get('name') or 'tool'} — {data['state']}{duration}") + tool(data) elif name == "status": self.state = {"busy": "Working", "connecting": "Connecting"}.get(data["state"], "Ready") if self.state == "Connecting": @@ -328,7 +348,8 @@ def execute(context, is_interactive): history = context.space_data.history if not history or not (text := history[-1].body.strip()): return {"CANCELLED"} - _append("INPUT", "> " + text) + if text.startswith("/"): + _append("INPUT", "> " + text) bpy.ops.console.history_append(text="", current_character=0, remove_duplicates=True) chat.active = True _sync(_append) diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 16eb58ba2c491b29289b839bbb13d642c5863bd9..0c3a1e1f2b6dd2a5bfbbbd62242c0c911c638138 100644 GIT binary patch delta 1817 zcmZWpeQZ-z6n}k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br8e#eD?k+lLfz>&u7<=$~!nKKs&j77mIz+LXHspzy~&LHPE&C zymSkeji%LpJr8RMyU06UEjrQXr+s;-1rPYC`ojp`@Kd*qUHE)}{)jI?>##nq4Wh(3 zgx>`qqVG6n!lDzVDvUPMYDZ7vNHg&4+cPF6EK>m!OSF6iQSTt7u^d{(F;FfSr{tH|GPsv#&Z80Y9EIHBVlS&|0RxvVT=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "a99bdb0e685bfad38b28db41ec8f00cb0c35ec793af1f551828235ac47f2accb" + "sha256": "dc6ae2fd74c2db855e5ca23a3c77f595dea8a3a34da62d91d7539b9190c4f66b" } } } diff --git a/integrations/blender/test/console-chat.test.ts b/integrations/blender/test/console-chat.test.ts index e54a569..5c11fa8 100644 --- a/integrations/blender/test/console-chat.test.ts +++ b/integrations/blender/test/console-chat.test.ts @@ -44,7 +44,32 @@ it("the sidecar resumes a folder conversation and streams wrapped tool names and prompt: async (value: unknown) => calls.push(value), interrupt: async (value: unknown) => calls.push(value), }, - message: { list: async () => ({ data: [] }) }, + message: { + list: async (input: unknown) => { + assert.deepEqual(input, { sessionID: session.id, order: "desc", limit: 21 }) + return { + data: [ + { + type: "assistant", + content: [ + { + type: "tool", + name: "execute", + state: { status: "completed", input: { code: 'return search("context")' } }, + }, + { + type: "tool", + name: "execute", + state: { status: "completed", input: { code: "return tools.blender.context({})" } }, + }, + { type: "text", text: "Scene read." }, + ], + }, + ...Array.from({ length: 20 }, (_, i) => ({ type: "user", text: `Question ${i + 1}` })), + ], + } + }, + }, model: { list: async () => ({ data: [] }), default: async () => ({ data: { providerID: "ok", id: "model" } }) }, event: { subscribe: async function* ({ signal }: { signal: AbortSignal }) { @@ -95,6 +120,18 @@ it("the sidecar resumes a folder conversation and streams wrapped tool names and }) assert.ok(out.some((item) => JSON.stringify(item).includes('"resumed":true'))) assert.equal(bindings.get(session.id), "offer_here") + const recent = ( + out.find((item) => (item as { event?: string }).event === "history") as { + data: { messages: unknown[] } + } + ).data.messages + assert.deepEqual(recent[0], { role: "system", text: "Earlier messages are available in OpenCode." }) + assert.deepEqual(recent[1], { role: "user", text: "Question 19" }) + assert.deepEqual(recent.slice(-3), [ + { role: "user", text: "Question 1" }, + { role: "tool", text: "blender_context / completed", name: "blender_context", state: "completed" }, + { role: "assistant", text: "Scene read." }, + ]) out.length = 0 await call("prompt", { text: "hello" }) await emit("session.text.delta", { delta: "not ours" }, "ses_codenomad") diff --git a/integrations/blender/test/console_chat_test.py b/integrations/blender/test/console_chat_test.py index 12e9cc0..dfcec39 100644 --- a/integrations/blender/test/console_chat_test.py +++ b/integrations/blender/test/console_chat_test.py @@ -34,6 +34,25 @@ def test_lines(self): self.assertEqual(lines.feed("", end=True), ["Tail"]) self.assertEqual(lines.feed("## prose\n"), ["prose"]) + def test_history_clears_and_uses_live_formats(self): + chat = console.Chat() + rows = [] + append = lambda kind, text: rows.append((kind, text)) + chat._event({"event": "assistant_delta", "data": {"text": "stale"}}, append) + chat._event({"event": "history", "data": {"messages": [ + {"role": "user", "text": "Read the scene."}, + {"role": "tool", "text": "blender_context / completed", "name": "blender_context", "state": "completed"}, + {"role": "assistant", "text": "**Done.**"}, + ]}}, append) + chat._event({"event": "assistant_delta", "data": {"text": "Live reply\n"}}, append) + self.assertEqual(rows, [ + ("CLEAR", ""), + ("INPUT", "> Read the scene."), + ("INFO", "Tool: blender_context — completed"), + ("OUTPUT", "Done."), + ("OUTPUT", "Live reply"), + ]) + def test_timer_broadcasts_complete_lines_only_to_opencode_areas(self): context = console.bpy.context = NS() diff --git a/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py b/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py index 567ccc2..eea4cc2 100644 --- a/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py +++ b/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py @@ -160,6 +160,7 @@ def __event( self, name, data ) : elif name == "model" : self.__setModel( str( data.get( "selected", "" ) ) ) elif name == "history" : + self.__streaming = False self.__transcript.setText( "" ) for message in data.get( "messages", [] ) : self.__append( message.get( "role", "system" ), message.get( "text", "" ) ) diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index 8c878630435c06a596b76929bc15b91cb06a5053..6404ca2ded8e3770ac90ef4e4ca735f94d425bd5 100644 GIT binary patch delta 658 zcmZWn&ubGw6yDug3auy=>WUi5V=rbgEUi!)DjLKH1}hOQQW4SV<|SF(%!ZlSXt6~L zf&@eakwK;C&6{3?)suo4dhriX@Gr1<@a~Vvwp617!<+fu_r5ppV_tVhzuXV!NR`|SVkRUANhNCd2JnQjkTqt&)fkuh z=oWOEBW?W$Bj+*K%sLGttZ7~lx7ra(tZ8uT?85SewwCgMkVz{6b6`|C=7bx`5ZgQ1?D~P&P);u`v{TKPzJsgrBO8QPG~fb@Qkq^5fMi43RD*2wzI@YcUk4~g9*FQ%;rN5N5! iZI9>v{1nsJX8gVO7S(Cnp0=L+R9)NlhQ67$PX7iPXxOI! delta 280 zcmccHBe0`WprM6v3zH!e@AZpiw>3-|7(iHavb}=D_An-UK2b|VX>?M4>NuM?-wU%@Q8-D?)J1@m-?dCc0X1&Ku^dc`G)C8_pcsAlC8k8H0#!F-T$ zdcX;0Db&69xzC=CEk C0bN-D diff --git a/integrations/gaffer/plugin/package.json b/integrations/gaffer/plugin/package.json index b8528f6..e87037c 100644 --- a/integrations/gaffer/plugin/package.json +++ b/integrations/gaffer/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.3.0", "appVersions": ">=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "bc7cc5e2a75ed4f9ab981bc6bdec3939ee3ffe95ef03b19ca2267dc5f7f5103a" + "sha256": "31bbd2e679a08b0a494c8772295f76c43daec65d1521536cec8977ae895a87db" } } } diff --git a/integrations/godot/host/addons/opencode_link/dock.gd b/integrations/godot/host/addons/opencode_link/dock.gd index 7571e25..57d450e 100644 --- a/integrations/godot/host/addons/opencode_link/dock.gd +++ b/integrations/godot/host/addons/opencode_link/dock.gd @@ -366,6 +366,7 @@ func _event(name: String, data: Dictionary) -> void: "agent": _agent_label.text = str(data.get("agent", "")) "history": + _streaming = false _transcript.clear() for message in data.get("messages", []): _append(str(message.get("role", "system")), str(message.get("text", ""))) diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index 563a6173d36d3390b8a0076bd824b129ad1e0abc..1e6e53a264f26324d091af55a310975c50fc06ce 100644 GIT binary patch delta 719 zcmZWnL2DCH5YCRJqM-*tt5^b)y_jHF+8RqyGzU?PC_$|UTg5(;NwT_m8{WQ+mNY~V zYR`st4<5XD6RV+z{R1M17g4;_Lwhn2RO$~9e7h;p=)mK>`DWgHGavKdL-gsV=&Rb$ zo@ICYd3`DpsjoMOE*mXO$JakkUi&f9+^8BP7X$m+N3AgSvimB)naIm)rNa?lqR+ z`2H}jF`q)tDin~b-u#bC@a@RH!7+~Fg!gL=V&3K&Z0$@UC{J9fQOc$xZLyH3kmIlt zIYxm=W;m9ar^I+_P>`e{s7At}L^64DFNS6o@t?mI@scd#>A}CaxQGEqGbG8o!m&lh z;B;RmcPb(FnlfDOl+B_{D3xuC0*MzKNfjlWRO!k;%YE7*3+KL5d}%;B8=4x~ikBZxoU@D-DkEW&?`3n+a diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json index aab89ad..f2cb667 100644 --- a/integrations/godot/plugin/package.json +++ b/integrations/godot/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.1.0", "appVersions": ">=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "2f20561a8949d8a3fec63e65a2866f7df5792559d09a00ce6e1544325b7dfe7f" + "sha256": "0c01eed4a1f30ae09f191d6a3ce29688d00cc9cfae3437c5b0c5bfcdfc075203" } } } diff --git a/integrations/houdini/host/scripts/opencode_houdini/panel.py b/integrations/houdini/host/scripts/opencode_houdini/panel.py index 695ebc7..0159a40 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/panel.py +++ b/integrations/houdini/host/scripts/opencode_houdini/panel.py @@ -333,6 +333,7 @@ def _event(self, channel: str, name: str, data: dict) -> None: self._connected = True self._append("system", "Resumed session" if data.get("resumed") else "New session") elif name == "history": + self._streaming = False self._transcript.clear() for message in data.get("messages", []): self._append(message.get("role", "system"), message.get("text", "")) diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip index 395d399719251ab65a6eb1a0877a0b050472e44d..ea2951f3e3bcbada826ba7eb3784bc7c085cd27f 100644 GIT binary patch delta 672 zcmZWnO=uHA6y9+_Oe7RRA<(MNMKsZLX$6B=GzSq3DnXNrh_qw!k}U4dhM7q;+E7LC z=PWXK^I|E{V_{M0K_~?;dJ(*+jo?YW_Toh+Yluc44DZc*-~0P`E3d}Bu8!SYChcxw z-}3#9mD85he|sLhRTKKnI^7a>yQG`dKfaK?Vd*p3$j0B@nVe3n5i7BFx0u`%7L)WF zOSYJRQ~6@4aQ?#Vnf%#&368;`shPOmeUI)4i`VH9x=;?dR3H^oXrebjG&y&9?I_sB zCzLVmj0p>5{(o*1A`k{yWv+)6gDVGq!$XA?;~d&HbS^ebDJN=@i&RrWE(f-KDG})= zzrus7+}5``^zilw*O|)zXFm3uo7uwm9r}I$w$W`4!n7ufbf-S>j85pEPw47k9f4)! z%Is5jr3yql<)f6WhSI4p#T@CmWlT+FM#)J#0$V5~rqbz|I7H%B;h$U&c}>;f_-HQ7 z&qKe*Le!+(6fzJwhvPMs9#jJOJ(SbrvhG$@%1|A6*yp(|75aufW#Hz2k_pd65!LIL z111ny%W%vtdk8LvLIe4Upn{H}b~vh;ohyBNiH^qx>vz)O%SHN{=nv0nEd01cUu0v$ pd(w~B=^UwP(xV0PRG;h7$?-o&M69jW-!iKo_2{n64?j`k{RPX(4ea zBa93!N7~CJn6{ToFuzXRURA~H%RD`{j#+!UZXL5YS7}~$UVeF=Qf=21.0", "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "e77903d8cd907e92fceac47bf7d707cd610706210762a6e34663dca9c3e16538" + "sha256": "9197d5223fa4ae1e2715ef68a7d2374798197330f22b51b9e72cb1c115167521" } } } diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts index ff4c57d..1247e78 100644 --- a/packages/integration-kit/src/panel.ts +++ b/packages/integration-kit/src/panel.ts @@ -1,7 +1,7 @@ // An in-app chat is a plain client: attach its conversation to the host's existing offer, never announce one. import { normalize } from "node:path" -import type { OpenCode } from "@opencode/client" +import type { OpenCode, SessionMessageInfo } from "@opencode/client" import { rpcDefinition } from "./contract.ts" import { requestHost as kitRequestHost } from "./host-client.ts" @@ -91,8 +91,7 @@ export function briefly(error: unknown) { const modelKey = (model: ModelRef | undefined) => model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" -type Part = { type?: string; text?: string; name?: string; state?: { status?: string; input?: unknown } } -type Message = { type?: string; text?: string; content?: Part[] } +const HISTORY_LIMIT = 20 type Conversation = { id: string; title?: string; time?: { updated?: number } } function conversationEntry({ id, title, time }: Conversation) { @@ -114,7 +113,7 @@ type EventData = { model?: ModelRef } -function history(messages: ReadonlyArray) { +function history(messages: ReadonlyArray) { return messages.flatMap((message) => { if (message.type === "user") return [{ role: "user", text: message.text ?? "" }] if (message.type !== "assistant") return [] @@ -123,7 +122,11 @@ function history(messages: ReadonlyArray) { if (part.type === "tool") { const name = toolDisplay(part.name || "tool", part.state?.input) if (name === null) return [] - return [{ role: "tool", text: `${name} / ${part.state?.status ?? "unknown"}` }] + const state = + { running: "starting", streaming: "starting", error: "failed", completed: "completed" }[ + part.state?.status ?? "" + ] ?? "unknown" + return [{ role: "tool", text: `${name} / ${state}`, name, state }] } return [] }) @@ -373,13 +376,17 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { channels.set(id, c) const [messages, models, configured, active] = await step("loading the conversation", () => Promise.all([ - service.message.list({ sessionID: c.sessionID, order: "desc", limit: 200 }), + service.message.list({ sessionID: c.sessionID, order: "desc", limit: HISTORY_LIMIT + 1 }), service.model.list({ location: { directory } }), service.model.default({ location: { directory } }), service.session.active(), ]), ) if (!c.model && configured.data) c.model = configured.data as ModelRef + const recent = history(messages.data.slice(0, HISTORY_LIMIT).reverse()) + if (messages.data.length > HISTORY_LIMIT || messages.cursor?.next) + recent.unshift({ role: "system", text: "Earlier messages are available in OpenCode." }) + event(c, "history", { messages: recent }) event(c, "session", { id: c.sessionID, resumed: Boolean(known), @@ -393,7 +400,6 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { .filter((model) => model.enabled) .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), }) - event(c, "history", { messages: history([...messages.data].reverse() as never) }) event(target, "conversations", { selected: session.id, entries: (known ? sessions : [session, ...sessions]).map(conversationEntry), From a8fa7ef5fc0d71b970689b669a544a88d33855fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 00:58:33 +0100 Subject: [PATCH 11/13] Only show the history notice when older messages exist --- .../host/blender/opencode_link-0.4.8.zip | Bin 1001297 -> 1001272 bytes integrations/blender/plugin/package.json | 2 +- .../host/gaffer/opencode_link-0.3.0.zip | Bin 263773 -> 263748 bytes integrations/gaffer/plugin/package.json | 2 +- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 191135 -> 191110 bytes integrations/godot/plugin/package.json | 2 +- .../host/houdini/opencode_link-0.3.1.zip | Bin 254570 -> 254545 bytes integrations/houdini/plugin/package.json | 2 +- packages/integration-kit/src/panel.ts | 2 +- packages/integration-kit/test/panel.test.ts | 3 ++- 10 files changed, 7 insertions(+), 6 deletions(-) diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index 0c3a1e1f2b6dd2a5bfbbbd62242c0c911c638138..e73ed016ac475c455950bb383ecbb038866c6c35 100644 GIT binary patch delta 129 zcmccEXS<`%wxNZwg{g(Pg{6hHg{_6Xg`C?Zv@mn%7O*eGsmtre7<7Z%C008+LEOh_? delta 197 zcmdndXM3^FwxNZwg{g(Pg{6hHg{_6Xg`s5rmKUN0}TqNM%MLLMOI-F|2xU+fYj&C@mA_&qrS zZ}KpdBo=2+XSCuMncnBdFU4{4KTs$mGjIAubAI9Jr5$_%+zfEgF#VnzzonwI96v*O bW>KnML1ln9D;r4K4hUBZFfdFo;|KBpE-*Zn diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index b81ee61..75fae87 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.4.8", "appVersions": ">=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "dc6ae2fd74c2db855e5ca23a3c77f595dea8a3a34da62d91d7539b9190c4f66b" + "sha256": "7638ffdc16cac5158e2ff3e752e39722528751985e0d11adb2d5535b7eece2a7" } } } diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index 6404ca2ded8e3770ac90ef4e4ca735f94d425bd5..507b18810a07dd431aae7ecda9ddae2b464c5fba 100644 GIT binary patch delta 68 zcmccHBXFcgprM6v3zLQgXLNt7wf!+h2K#nH3#RRc7R=N8w?912{KFO@GyM@Oix*?l QbX_(UEw-zSEDQ_`07@Pe-T(jq delta 101 zcmX@oBXGAzprM6v3zLQg=ki;h)<+y;WQb@tv|!q9Xu&+aUs9o_Mj=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "31bbd2e679a08b0a494c8772295f76c43daec65d1521536cec8977ae895a87db" + "sha256": "e7d9af005d7a86096e24c62a17e5d554a450b3c33c4959aee2b50b9647a1370e" } } } diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index 1e6e53a264f26324d091af55a310975c50fc06ce..e663491ae8415a9acfefbff4fd7f60b2b6ba76dc 100644 GIT binary patch delta 59 zcmbP#mAmaKcf%G&H$_gT2GjR}#~2v`+x-<8xBDwHt?Az`vXRN$5+O4^%02%ocf%G&H$~3+TLm3i#~2y1+Wi$7xBDwHt?8FksHsuNO)V}?OiwM=OD-)c i&M&gp%S){&+5US2ler~A&vffoOs;GXo-;8pFaQ98zaS3) diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json index f2cb667..c86c087 100644 --- a/integrations/godot/plugin/package.json +++ b/integrations/godot/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.1.0", "appVersions": ">=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "0c01eed4a1f30ae09f191d6a3ce29688d00cc9cfae3437c5b0c5bfcdfc075203" + "sha256": "1057888465deb6edb41ac9b5299d521c6614ad3303290797870f8c8a577ea060" } } } diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip index ea2951f3e3bcbada826ba7eb3784bc7c085cd27f..ae57b1569c58a0b49d14c647a1480f21b2440d4f 100644 GIT binary patch delta 63 zcmaELg#Y3Z{)QIDEljx*TziU-xqUgx$nfQ8d$|PD_Hqg4Y5m*PRxq<#AxTX)eZ;KK LR&$S;fq?-4a=;m) delta 89 zcmcb3g#XnM{)QIDEljx*Tvyt34SA0-GVmU2FPC82UM|5rtzS~1rbZz*wYWGjJ+)Xb lxwNP_zsO!MFSVj%JMRi+Rx2b;(`6np>$6S0$IQUM006xy9*h70 diff --git a/integrations/houdini/plugin/package.json b/integrations/houdini/plugin/package.json index d64d5c7..7244ea1 100644 --- a/integrations/houdini/plugin/package.json +++ b/integrations/houdini/plugin/package.json @@ -64,7 +64,7 @@ "range": "^0.3.1", "appVersions": ">=21.0", "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "9197d5223fa4ae1e2715ef68a7d2374798197330f22b51b9e72cb1c115167521" + "sha256": "410cb95b95b3c5de86d250c20833b5765c402e45889abdedce452885e174bd9e" } } } diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts index 1247e78..b6c09d9 100644 --- a/packages/integration-kit/src/panel.ts +++ b/packages/integration-kit/src/panel.ts @@ -384,7 +384,7 @@ export function createPanel(config: PanelHost, deps: PanelDependencies) { ) if (!c.model && configured.data) c.model = configured.data as ModelRef const recent = history(messages.data.slice(0, HISTORY_LIMIT).reverse()) - if (messages.data.length > HISTORY_LIMIT || messages.cursor?.next) + if (messages.data.length > HISTORY_LIMIT) recent.unshift({ role: "system", text: "Earlier messages are available in OpenCode." }) event(c, "history", { messages: recent }) event(c, "session", { diff --git a/packages/integration-kit/test/panel.test.ts b/packages/integration-kit/test/panel.test.ts index 17bfc32..d3c948f 100644 --- a/packages/integration-kit/test/panel.test.ts +++ b/packages/integration-kit/test/panel.test.ts @@ -69,7 +69,7 @@ it("queues during startup, starts drafts lazily and selects/rebinds folder conve active: async () => ({}), }, model: { list: async () => ({ data: [] }), default: async () => ({}) }, - message: { list: async () => ({ data: [] }) }, + message: { list: async () => ({ data: [], cursor: { next: "end" } }) }, event: { subscribe: async function* ({ signal }: { signal: AbortSignal }) { await new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true })) @@ -115,6 +115,7 @@ it("queues during startup, starts drafts lazily and selects/rebinds folder conve assert.equal(prompt.length, 0) label = "v001" await until(() => prompt.length === 1) + assert.deepEqual(out.findLast(({ event }) => event === "history")?.data.messages, []) assert.equal(sessions[0]?.title, "OpenCode default") assert.deepEqual(prompt[0], { sessionID: "created-0", text: "early" }) assert.deepEqual( From dda771e07801cb831666ad060d527df56c4f7203 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 01:00:35 +0100 Subject: [PATCH 12/13] Hide the default model variant in in-app chat --- .../host/blender/opencode_link-0.4.8.zip | Bin 1001272 -> 1001303 bytes integrations/blender/plugin/package.json | 2 +- .../blender/test/console-chat.test.ts | 10 +++++++++- .../host/gaffer/opencode_link-0.3.0.zip | Bin 263748 -> 263779 bytes integrations/gaffer/plugin/package.json | 2 +- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 191110 -> 191141 bytes integrations/godot/plugin/package.json | 2 +- .../host/houdini/opencode_link-0.3.1.zip | Bin 254545 -> 254576 bytes integrations/houdini/plugin/package.json | 2 +- packages/integration-kit/src/panel.ts | 4 +++- 10 files changed, 16 insertions(+), 6 deletions(-) diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip index e73ed016ac475c455950bb383ecbb038866c6c35..98dc095a3e30a38e7567891eee9138aee59a506e 100644 GIT binary patch delta 202 zcmdndXM4TRwxNZwg{g(Pg{6hHg{_6Xg`3Tmo1c=JqgR$#l$n@UqM&GNtDuyUnwD6aQ=-)VxtIrtdAENq=F_=^WWsb! zH-1l!@S8jgC5gq^(;2P!MW*+;@k?=>{|^+($jqC5(VSm+dT9rr05=01v`xR~#&4;p gD96uGo>`QtS5O(?&B_LnwgbY|0t^h(%=m#k02$Ofvj6}9 delta 171 zcmccKXS<`%wxNZwg{g(Pg{6hHg{_6Xg`G-T0+AHv9()Wn|_} zXEf&*o<606Pk@^N4$`Opb>p{GWRl}&D9=5.3", "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "7638ffdc16cac5158e2ff3e752e39722528751985e0d11adb2d5535b7eece2a7" + "sha256": "a32765bd057054daccf429ce23a74a023d043c7b7f099da7bce26fb620542577" } } } diff --git a/integrations/blender/test/console-chat.test.ts b/integrations/blender/test/console-chat.test.ts index 5c11fa8..c3912a4 100644 --- a/integrations/blender/test/console-chat.test.ts +++ b/integrations/blender/test/console-chat.test.ts @@ -19,7 +19,12 @@ it("the sidecar resumes a folder conversation and streams wrapped tool names and const out: unknown[] = [] const bindings = new Map([["ses_codenomad", "offer_here"]]) const location = { directory: import.meta.dirname } - const session = { id: "ses_console", agent: "build", time: { updated: 2 } } + const session = { + id: "ses_console", + agent: "build", + time: { updated: 2 }, + model: { providerID: "ok", id: "model", variant: "default" }, + } let push: (value: unknown) => void = () => {} const api = { rpc: (rpc: { id: string }) => { @@ -119,6 +124,7 @@ it("the sidecar resumes a folder conversation and streams wrapped tool names and registration: "service-example.json", }) assert.ok(out.some((item) => JSON.stringify(item).includes('"resumed":true'))) + assert.ok(out.some((item) => JSON.stringify(item).includes('"model":"ok/model"'))) assert.equal(bindings.get(session.id), "offer_here") const recent = ( out.find((item) => (item as { event?: string }).event === "history") as { @@ -163,6 +169,8 @@ it("the sidecar resumes a folder conversation and streams wrapped tool names and false, ) assert.deepEqual(out.at(-1), event("status", { state: "idle", interrupted: true })) + await emit("session.step.started", { model: { providerID: "ok", id: "model", variant: "high" } }) + assert.deepEqual(out.at(-1), event("profile", { agent: undefined, model: "ok/model#high" })) assert.deepEqual(calls, [ { sessionID: session.id, text: "hello" }, { sessionID: session.id, resume: false }, diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip index 507b18810a07dd431aae7ecda9ddae2b464c5fba..755a9c26577da332500f36f9e4d76596d9d42f37 100644 GIT binary patch delta 106 zcmX@oBk;IKprM6v3zLQgXVvaDx42`B3~}v-7EId>EtpRx%BiU-=1.6", "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "e7d9af005d7a86096e24c62a17e5d554a450b3c33c4959aee2b50b9647a1370e" + "sha256": "95e9e3086bd172541de755aacb2795a80aab48b896ad92e37c281d49a8e32885" } } } diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index e663491ae8415a9acfefbff4fd7f60b2b6ba76dc..8fbaed39724ebcf9830c326e2998d00e959e3707 100644 GIT binary patch delta 90 zcmZp>%Dwa|cf%G&H$~1)ImaUf#~2w3+Wi$7xBDwH-Aj~HQ&Y&zPf5+uD@!cOOw21$ mP_(sGP)bQnODxSPQQEH4%*2+C&^X=t6_YF5v*%0<3=9B?@g5HV delta 59 zcmZ2_mAmaKcf%G&H$_gT2GjR}#~2v`+x-<8xBDwH-Aml=)6B%0j*yui^@_=r?f7#h H1_lNIiDndJ diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json index c86c087..8dd0085 100644 --- a/integrations/godot/plugin/package.json +++ b/integrations/godot/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.1.0", "appVersions": ">=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "1057888465deb6edb41ac9b5299d521c6614ad3303290797870f8c8a577ea060" + "sha256": "d6f970ebd42b8b600cd8576b1d95cf96817e156b0b1930282856d094531936e3" } } } diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip index ae57b1569c58a0b49d14c647a1480f21b2440d4f..fffdbccbfbe8f16594ee0c72d2efaa3244e80a01 100644 GIT binary patch delta 94 zcmcb3g#W`4{)QIDEljx*T-kN&{e+J(G6)}QFPC82UM|6WB2i9FO(8cwB{fH{EU_pv qF|R~H(biT$DJ3;6u{5VdX}et&^ObZYozrC=G3&F=21.0", "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "410cb95b95b3c5de86d250c20833b5765c402e45889abdedce452885e174bd9e" + "sha256": "3fd582ac3a74bdfe1016d65cbf8935c49787450904984f19c6e14fcd5bd19694" } } } diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts index b6c09d9..3fa355c 100644 --- a/packages/integration-kit/src/panel.ts +++ b/packages/integration-kit/src/panel.ts @@ -89,7 +89,9 @@ export function briefly(error: unknown) { } const modelKey = (model: ModelRef | undefined) => - model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" + model + ? `${model.providerID}/${model.id}${model.variant && model.variant !== "default" ? `#${model.variant}` : ""}` + : "" const HISTORY_LIMIT = 20 type Conversation = { id: string; title?: string; time?: { updated?: number } } From fd6da9c558b26a905b76c8dff3d0d62e5a6746a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 20 Nov 2026 01:21:50 +0100 Subject: [PATCH 13/13] Bump Blender, Gaffer, Godot and Houdini feature releases --- catalog.json | 16 ++++++++-------- .../host/opencode_link/blender_manifest.toml | 2 +- integrations/blender/host/ops.json | 2 +- ...link-0.4.8.zip => opencode_link-0.5.0.zip} | Bin 1001303 -> 1001303 bytes integrations/blender/plugin/package.json | 8 ++++---- integrations/blender/test/plugin.test.ts | 2 +- integrations/blender/test/publication.test.ts | 2 +- integrations/gaffer/host/manifest.json | 2 +- ...link-0.3.0.zip => opencode_link-0.4.0.zip} | Bin 263779 -> 263779 bytes integrations/gaffer/plugin/package.json | 8 ++++---- .../host/addons/opencode_link/plugin.cfg | 2 +- ...link-0.1.0.zip => opencode_link-0.2.0.zip} | Bin 191141 -> 191141 bytes integrations/godot/plugin/package.json | 8 ++++---- integrations/houdini/host/manifest.json | 2 +- ...link-0.3.1.zip => opencode_link-0.4.0.zip} | Bin 254576 -> 254576 bytes integrations/houdini/plugin/package.json | 8 ++++---- package-lock.json | 8 ++++---- spec/README.md | 4 ++-- 18 files changed, 37 insertions(+), 37 deletions(-) rename integrations/blender/plugin/host/blender/{opencode_link-0.4.8.zip => opencode_link-0.5.0.zip} (99%) rename integrations/gaffer/plugin/host/gaffer/{opencode_link-0.3.0.zip => opencode_link-0.4.0.zip} (99%) rename integrations/godot/plugin/host/godot/{opencode_link-0.1.0.zip => opencode_link-0.2.0.zip} (99%) rename integrations/houdini/plugin/host/houdini/{opencode_link-0.3.1.zip => opencode_link-0.4.0.zip} (99%) diff --git a/catalog.json b/catalog.json index 7ac6b98..a38ed91 100644 --- a/catalog.json +++ b/catalog.json @@ -22,7 +22,7 @@ { "id": "blender", "package": "@neuralnomads/opencode-blender", - "range": "^0.4", + "range": "^0.5", "displayName": "OpenCode for Blender", "family": "native", "plugin": "neuralnomads.blender", @@ -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.8" }, + "host": { "protocol": 1, "range": "^0.5.0" }, "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"] } @@ -40,7 +40,7 @@ { "id": "gaffer", "package": "@neuralnomads/opencode-gaffer", - "range": "^0.3", + "range": "^0.4", "displayName": "OpenCode for Gaffer", "family": "native", "plugin": "neuralnomads.gaffer", @@ -50,7 +50,7 @@ "fr": "Lire, modifier et vérifier les scripts ouverts dans Gaffer depuis toute conversation OpenCode, avec un panneau facultatif dans Gaffer." }, "app": { "name": "Gaffer", "versions": ">=1.6" }, - "host": { "protocol": 1, "range": "^0.3.0" }, + "host": { "protocol": 1, "range": "^0.4.0" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/gaffer/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/gaffer/plugin"] } @@ -58,7 +58,7 @@ { "id": "godot", "package": "@neuralnomads/opencode-godot", - "range": "^0.1", + "range": "^0.2", "displayName": "OpenCode for Godot", "family": "native", "plugin": "neuralnomads.godot", @@ -68,7 +68,7 @@ "fr": "Lire, modifier et vérifier le projet ouvert dans l'éditeur Godot depuis toute conversation OpenCode : GDScript en une action d'annulation, vérifications et exécutions dans un Godot en arrière-plan, et un dock de conversation facultatif dans l'éditeur." }, "app": { "name": "Godot", "versions": ">=4.7 <5" }, - "host": { "protocol": 1, "range": "^0.1.0" }, + "host": { "protocol": 1, "range": "^0.2.0" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/godot/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/godot/plugin"] } @@ -76,7 +76,7 @@ { "id": "houdini", "package": "@neuralnomads/opencode-houdini", - "range": "^0.3", + "range": "^0.4", "displayName": "OpenCode for Houdini", "family": "native", "plugin": "neuralnomads.houdini", @@ -86,7 +86,7 @@ "fr": "Lire, modifier et vérifier la scène Houdini ouverte depuis toute conversation OpenCode, avec un panneau facultatif dans Houdini." }, "app": { "name": "Houdini", "versions": ">=21.0" }, - "host": { "protocol": 1, "range": "^0.3.1" }, + "host": { "protocol": 1, "range": "^0.4.0" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/houdini/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/houdini/plugin"] } diff --git a/integrations/blender/host/opencode_link/blender_manifest.toml b/integrations/blender/host/opencode_link/blender_manifest.toml index b4a1603..d93cf8d 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.8" +version = "0.5.0" name = "OpenCode Link" tagline = "Lets OpenCode work on this Blender session" maintainer = "NeuralNomads" diff --git a/integrations/blender/host/ops.json b/integrations/blender/host/ops.json index 830d8a8..eebe592 100644 --- a/integrations/blender/host/ops.json +++ b/integrations/blender/host/ops.json @@ -1,6 +1,6 @@ { "addon": "opencode_link", - "version": "0.4.8", + "version": "0.5.0", "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/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.5.0.zip similarity index 99% rename from integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip rename to integrations/blender/plugin/host/blender/opencode_link-0.5.0.zip index 98dc095a3e30a38e7567891eee9138aee59a506e..df44c70997834ffd17de58a10fbf3af244b1f10a 100644 GIT binary patch delta 94 zcmccKXM4TRwqXn7k$#rD>`$wvpXg_dWj56_XxEs)2*gZ4%nZaVK+FonY(UHo#2i4( e3B+7L%nigmK+L;cV*=mp^7@B;v_79uVH delta 94 zcmccKXM4TRwqXn7k$#rH7pG)QKhe(^%WR@&(XKIp5r~<9m>Gy!fS47C*?^cGh&h0m e6NtHhm>Y=5.3", - "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "a32765bd057054daccf429ce23a74a023d043c7b7f099da7bce26fb620542577" + "payload": "host/blender/opencode_link-0.5.0.zip", + "sha256": "b8ce9b3bd4dc89b4d94003ea1d04e7ea59af5724ab2f60e16d513b481bc3cf50" } } } diff --git a/integrations/blender/test/plugin.test.ts b/integrations/blender/test/plugin.test.ts index b320b9a..1931392 100644 --- a/integrations/blender/test/plugin.test.ts +++ b/integrations/blender/test/plugin.test.ts @@ -855,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\.8/) + await assert.rejects(other.tool("blender_context"), /no scene method: install OpenCode Link 0\.5\.0/) assert.ok(loaded) }) }) diff --git a/integrations/blender/test/publication.test.ts b/integrations/blender/test/publication.test.ts index 45aec3b..f9e898a 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.8") + assert.equal(pkg.version, "0.5.0") 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/gaffer/host/manifest.json b/integrations/gaffer/host/manifest.json index 9992a34..3cacd42 100644 --- a/integrations/gaffer/host/manifest.json +++ b/integrations/gaffer/host/manifest.json @@ -1 +1 @@ -{ "name": "OpenCode Link for Gaffer", "version": "0.3.0", "protocol": 1, "license": "MIT" } +{ "name": "OpenCode Link for Gaffer", "version": "0.4.0", "protocol": 1, "license": "MIT" } diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.4.0.zip similarity index 99% rename from integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip rename to integrations/gaffer/plugin/host/gaffer/opencode_link-0.4.0.zip index 755a9c26577da332500f36f9e4d76596d9d42f37..0607b32c65f27684dc9e2c068ed93382e9b8e0b6 100644 GIT binary patch delta 48 zcmaFdBk;IKU_&Ac3){};zLQf~d>KueH?y>FW?=+krtO<+j^0v8b^C0LZ!# AQ2+n{ delta 48 zcmaFdBk;IKU_&AcOQ6@S?UPekd>M_KH?y>FW?=+krtO<+j^0v8b^C0MX+S A!T=1.6", - "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "95e9e3086bd172541de755aacb2795a80aab48b896ad92e37c281d49a8e32885" + "payload": "host/gaffer/opencode_link-0.4.0.zip", + "sha256": "974f1c670359218641153e24ee46f6c90b372372aaf2abaa64f7bf34ad90c0d1" } } } diff --git a/integrations/godot/host/addons/opencode_link/plugin.cfg b/integrations/godot/host/addons/opencode_link/plugin.cfg index 2c462dc..9db6aa3 100644 --- a/integrations/godot/host/addons/opencode_link/plugin.cfg +++ b/integrations/godot/host/addons/opencode_link/plugin.cfg @@ -3,5 +3,5 @@ name="OpenCode Link" description="Offers this project to OpenCode, and the OpenCode dock." author="NeuralNomads" -version="0.1.0" +version="0.2.0" script="plugin.gd" diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.2.0.zip similarity index 99% rename from integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip rename to integrations/godot/plugin/host/godot/opencode_link-0.2.0.zip index 8fbaed39724ebcf9830c326e2998d00e959e3707..65c6e82bd790380c4b29304ccbdd19070aa20abe 100644 GIT binary patch delta 44 ycmZ2_m3!$`?hW6kvOJoZ`C{_#sT&!Mn%7QiUptL)``T$tML}Tk?aD8iniv5aD;9?U delta 44 ycmZ2_m3!$`?hW6kvYav~-!S?2)QyaW&1=4.7 <5", - "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "d6f970ebd42b8b600cd8576b1d95cf96817e156b0b1930282856d094531936e3" + "payload": "host/godot/opencode_link-0.2.0.zip", + "sha256": "43059cb68ada77d6cb55cf9d20b745c07ca46455a68c12551c1034ad7701e127" } } } diff --git a/integrations/houdini/host/manifest.json b/integrations/houdini/host/manifest.json index c70c9a5..78b577b 100644 --- a/integrations/houdini/host/manifest.json +++ b/integrations/houdini/host/manifest.json @@ -1 +1 @@ -{ "name": "OpenCode Link", "version": "0.3.1", "protocol": 1, "license": "MIT", "appVersions": ">=21.0" } +{ "name": "OpenCode Link", "version": "0.4.0", "protocol": 1, "license": "MIT", "appVersions": ">=21.0" } diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.4.0.zip similarity index 99% rename from integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip rename to integrations/houdini/plugin/host/houdini/opencode_link-0.4.0.zip index fffdbccbfbe8f16594ee0c72d2efaa3244e80a01..95a6914b5b264b27c819aa1cda050aa14358622c 100644 GIT binary patch delta 50 zcmexxg#W`4{tY`gSpJ7r%$mH1!-?5M&!Cx+vz?KX5r~<#GjcM^UIWW+SGv#a#|!}O C+!1a7 delta 50 zcmexxg#W`4{tY`gScLoc{hPdp!-?5g&#;-1vz?KX5r~<#GjcM^UIWW+SGv#a#|!}J CW)WTh diff --git a/integrations/houdini/plugin/package.json b/integrations/houdini/plugin/package.json index 1cde9da..95ecd77 100644 --- a/integrations/houdini/plugin/package.json +++ b/integrations/houdini/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@neuralnomads/opencode-houdini", - "version": "0.3.1", + "version": "0.4.0", "description": "OpenCode for Houdini: read, change and check the open Houdini scene from any OpenCode conversation, with an optional panel inside Houdini.", "license": "MIT", "type": "module", @@ -61,10 +61,10 @@ "host": { "app": "houdini", "protocol": 1, - "range": "^0.3.1", + "range": "^0.4.0", "appVersions": ">=21.0", - "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "3fd582ac3a74bdfe1016d65cbf8935c49787450904984f19c6e14fcd5bd19694" + "payload": "host/houdini/opencode_link-0.4.0.zip", + "sha256": "7f46420f11134743afcae64115c62e2ab4a17e3481cf22b26abaabe305915b7a" } } } diff --git a/package-lock.json b/package-lock.json index 4786feb..7ebf255 100644 --- a/package-lock.json +++ b/package-lock.json @@ -39,7 +39,7 @@ }, "integrations/blender/plugin": { "name": "@neuralnomads/opencode-blender", - "version": "0.4.8", + "version": "0.5.0", "license": "MIT AND GPL-3.0-or-later", "devDependencies": { "@opencode/client": "2.2.5", @@ -57,7 +57,7 @@ }, "integrations/gaffer/plugin": { "name": "@neuralnomads/opencode-gaffer", - "version": "0.3.0", + "version": "0.4.0", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", @@ -75,7 +75,7 @@ }, "integrations/godot/plugin": { "name": "@neuralnomads/opencode-godot", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", @@ -93,7 +93,7 @@ }, "integrations/houdini/plugin": { "name": "@neuralnomads/opencode-houdini", - "version": "0.3.1", + "version": "0.4.0", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", diff --git a/spec/README.md b/spec/README.md index fec5418..2d00455 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.8", + "range": "^0.5.0", "appVersions": ">=5.3", - "payload": "host/blender/opencode_link-0.4.8.zip", + "payload": "host/blender/opencode_link-0.5.0.zip", "sha256": "" } }