From e6e002a762e82ea0da3651a615379dc242a02a98 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:15:57 +1000 Subject: [PATCH 1/2] feat(plugins): zero-build TSX/JSX plugins and native auxiliary-window EventRouter - Pin all 21 `anomalyco/rune` dependencies to `6f0df42b84991341134f5dea59aad0ac73bd59ac` (zero-build `.tsx`/`.jsx`, deferrable `RoutedEvent` & `EventRouter`, emoji caret, `AbortSignal.any`). - Replace `@rune/ui` JS monkey-patching (`WRAP_UI_JS`, `AuxUiWrapCache`, `WrapState`, `WrapScope`) in `apps/desktop/src/plugin_host/aux_windows/dispatch.rs` with Rune's native `Script::set_event_router`, `Script::with_event_tag`, and owned deferrable `RoutedEvent` (-452/+80 lines). - Support `.tsx` and `.jsx` plugin modules across `opencode-plugin-runtime` (`is_script`, `script_sources` fallback `init.js` -> `init.ts` -> `init.tsx` -> `init.jsx`, console source locations) and `apps/desktop/build.rs`. - Add ambient `__rune_jsx`, `__rune_frag`, `UiLibrary.{h,Fragment}`, `JSX.IntrinsicElements` for all 52 contract UI nodes, and JSX compiler options in `opencode-plugin-spec` codegen (`plugins/opencode.d.ts`, `plugins/tsconfig.json`). - Add `--tsx` template mode to `scripts/new-plugin.{mjs,ps1,sh}`. --- Cargo.lock | 64 +-- Cargo.toml | 42 +- apps/desktop/build.rs | 5 +- .../src/plugin_host/aux_windows/dispatch.rs | 532 +++--------------- .../src/plugin_host/aux_windows/mod.rs | 22 +- apps/desktop/src/plugin_host/runtime/hot.rs | 2 +- crates/opencode-plugin-runtime/src/console.rs | 14 +- crates/opencode-plugin-runtime/src/hot.rs | 4 +- crates/opencode-plugin-runtime/src/sources.rs | 45 +- crates/opencode-plugin-spec/src/codegen/ts.rs | 36 +- plugins/opencode.d.ts | 77 +++ plugins/tsconfig.json | 9 +- scripts/new-plugin.mjs | 218 ++++++- scripts/new-plugin.ps1 | 3 +- scripts/new-plugin.sh | 4 +- 15 files changed, 508 insertions(+), 569 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3d864946..aa047be16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,7 +26,7 @@ dependencies = [ [[package]] name = "accesskit_atspi_common" version = "0.21.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "accesskit", "accesskit_consumer", @@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "accesskit_macos" version = "0.27.2" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "accesskit", "accesskit_consumer", @@ -80,7 +80,7 @@ dependencies = [ [[package]] name = "accesskit_windows" version = "0.35.2" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "accesskit", "accesskit_consumer", @@ -2502,7 +2502,7 @@ checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" [[package]] name = "naga" version = "30.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "arrayvec", "bit-set", @@ -4263,7 +4263,7 @@ checksum = "9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3" [[package]] name = "parley_engine" version = "0.12.0" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "fontique", "harfrust", @@ -4566,7 +4566,7 @@ dependencies = [ [[package]] name = "procwatch" version = "0.1.0" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "libc", ] @@ -4955,7 +4955,7 @@ dependencies = [ [[package]] name = "rune" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "accesskit", "accesskit_android", @@ -5031,7 +5031,7 @@ dependencies = [ [[package]] name = "rune-core" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "js-sys", "libc", @@ -5061,7 +5061,7 @@ dependencies = [ [[package]] name = "rune-edit" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "js-sys", "parley", @@ -5075,7 +5075,7 @@ dependencies = [ [[package]] name = "rune-gpu" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "blake3", "bytemuck", @@ -5103,7 +5103,7 @@ dependencies = [ [[package]] name = "rune-highlights" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "unicode-ident", "wasmparser 0.245.1", @@ -5112,7 +5112,7 @@ dependencies = [ [[package]] name = "rune-i18n" version = "0.1.0" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "fixed_decimal", "icu_decimal", @@ -5132,7 +5132,7 @@ dependencies = [ [[package]] name = "rune-image" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "avif-parse", "blake3", @@ -5154,7 +5154,7 @@ dependencies = [ [[package]] name = "rune-kit" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "icu_normalizer", "js-sys", @@ -5175,7 +5175,7 @@ dependencies = [ [[package]] name = "rune-knobs" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "rune", ] @@ -5183,7 +5183,7 @@ dependencies = [ [[package]] name = "rune-mac" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "objc2 0.6.5", "rune-notify", @@ -5192,7 +5192,7 @@ dependencies = [ [[package]] name = "rune-media" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "ash", "blake3", @@ -5223,7 +5223,7 @@ dependencies = [ [[package]] name = "rune-mermaid" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "rune", ] @@ -5231,12 +5231,12 @@ dependencies = [ [[package]] name = "rune-motion" version = "0.1.0" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" [[package]] name = "rune-notify" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "async-channel", "async-io", @@ -5259,7 +5259,7 @@ dependencies = [ [[package]] name = "rune-perf" version = "0.1.0" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "procwatch", "serde_json", @@ -5268,7 +5268,7 @@ dependencies = [ [[package]] name = "rune-psychoscript" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "notify", "oxc_allocator", @@ -5287,7 +5287,7 @@ dependencies = [ [[package]] name = "rune-register" version = "0.1.0" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "linkme", ] @@ -5295,7 +5295,7 @@ dependencies = [ [[package]] name = "rune-spell" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", @@ -5308,7 +5308,7 @@ dependencies = [ [[package]] name = "rune-staging" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "wgpu", "windows", @@ -5317,7 +5317,7 @@ dependencies = [ [[package]] name = "rune-taffy" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "stacker", "taffy", @@ -5326,7 +5326,7 @@ dependencies = [ [[package]] name = "rune-text" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "bytemuck", "fontique", @@ -5355,7 +5355,7 @@ dependencies = [ [[package]] name = "rune-theme-opencode" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "rune", "rune-kit", @@ -5365,7 +5365,7 @@ dependencies = [ [[package]] name = "rune-tiny-skia-path" version = "0.11.4" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "arrayref", "bytemuck", @@ -5607,7 +5607,7 @@ dependencies = [ [[package]] name = "sctk-adwaita" version = "0.10.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "log", "smithay-client-toolkit", @@ -7107,7 +7107,7 @@ dependencies = [ [[package]] name = "wgpu-hal" version = "30.0.1" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "android_system_properties", "arrayvec", @@ -7507,7 +7507,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/anomalyco/rune?rev=3845da27466cc649437e1543cb51b8ec115df99c#3845da27466cc649437e1543cb51b8ec115df99c" +source = "git+https://github.com/anomalyco/rune?rev=6f0df42b84991341134f5dea59aad0ac73bd59ac#6f0df42b84991341134f5dea59aad0ac73bd59ac" dependencies = [ "ahash", "android-activity", diff --git a/Cargo.toml b/Cargo.toml index bda84cb33..ed1a496a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,19 +76,19 @@ license = "MIT" # Rune's default features less two the app doesn't use: `embedded-fonts` (the app registers its own # faces, so Rune's bundled Inter was 1.25 MB nobody drew with) and `ogg-audio` (Ogg and Opus audio # for macOS video, which apps/desktop turns on for macOS alone). -rune = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c", default-features = false, features = ["accessibility", "dbus", "metal-backend", "svg", "x11"] } -rune-kit = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-mermaid = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-theme-opencode = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-fx = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-i18n = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -procwatch = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-knobs = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-mac = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-notify = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-perf = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-register = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } -rune-psychoscript = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +rune = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac", default-features = false, features = ["accessibility", "dbus", "metal-backend", "svg", "x11"] } +rune-kit = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-mermaid = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-theme-opencode = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-fx = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-i18n = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +procwatch = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-knobs = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-mac = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-notify = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-perf = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-register = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } +rune-psychoscript = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } base64 = "0.22" polling = "3.11" # Objects keep their keys in the order they arrive, as JavaScript's do: a tool's arguments list as @@ -106,31 +106,31 @@ libmimalloc-sys = { path = "vendor/libmimalloc-sys" } # Rune's wgpu-hal (wgpu-hal as published plus `dx12::Instance::expose_adapter`, partial presents, and # removed-device fence handling, `vendor/wgpu-hal` in the Rune repo), at the Rune rev pinned above. # Keep the rev equal to the `rune` rev. -wgpu-hal = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +wgpu-hal = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Rune's winit (winit 0.30 as published plus `vendor/winit.patch`: a new Windows window isn't added again # to the taskbar it's already on, which cost CoInitializeEx and a TaskbarList COM object on the UI # thread before the first frame, and Wayland `content_corner_radius`). Keep the rev equal to the `rune` rev. -winit = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +winit = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Rune's sctk-adwaita (as published plus `vendor/sctk-adwaita.patch`: rounded bottom corners on Wayland # client-side frames and `AdwaitaFrame::content_corner_radius`). Keep the rev equal to the `rune` rev. -sctk-adwaita = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +sctk-adwaita = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Rune's accesskit_windows (0.35.2 as published plus `vendor/accesskit_windows.patch`: headings and # landmarks reach UI Automation; a field past 64 KiB keeps its text pattern). At the same rev as `rune`. -accesskit_windows = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +accesskit_windows = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Rune's accesskit_macos (0.27.2 as published plus `vendor/accesskit_macos.patch`: headings reach # VoiceOver as AppKit's AXHeading with their level; a field past 64 KiB keeps its line ranges). At the same # rev as `rune`. -accesskit_macos = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +accesskit_macos = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Rune's parley_engine (0.12.0 as published plus `vendor/parley_engine.patch`: UAX #9 rule L1 at a # paragraph's end, so Unicode's BidiTest.txt passes whole; segmenters and font metrics made once, # not for every text and run). Keep the rev equal to the `rune` rev. -parley_engine = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +parley_engine = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Rune's naga (30.0.1 as published plus `vendor/naga.patch`: constant-folding an expression to an earlier # handle neither stretches nor inverts an `Emit` range, gfx-rs/wgpu#7793; rune#1815). Keep the rev equal to the `rune` rev. -naga = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +naga = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Rune's accesskit_atspi_common (0.21.1 as published plus `vendor/accesskit_atspi_common.patch`: item roles read their # own `size_of_set`; rune#1819). Keep the rev equal to the `rune` rev. -accesskit_atspi_common = { git = "https://github.com/anomalyco/rune", rev = "3845da27466cc649437e1543cb51b8ec115df99c" } +accesskit_atspi_common = { git = "https://github.com/anomalyco/rune", rev = "6f0df42b84991341134f5dea59aad0ac73bd59ac" } # Keep dependencies lean in dev (opt-level = 1 cuts cold build time, RAM, and target/ size # across Windows/macOS/Linux), while keeping full -O3 on the small set of CPU-hot crates diff --git a/apps/desktop/build.rs b/apps/desktop/build.rs index b1bc2c89d..3e311deae 100644 --- a/apps/desktop/build.rs +++ b/apps/desktop/build.rs @@ -246,7 +246,10 @@ fn embed_js_plugins(manifest_dir: &std::path::Path, out: &std::path::Path) { } fn is_script(path: &str) -> bool { - path.ends_with(".js") || (path.ends_with(".ts") && !path.ends_with(".d.ts")) + path.ends_with(".js") + || path.ends_with(".jsx") + || path.ends_with(".tsx") + || (path.ends_with(".ts") && !path.ends_with(".d.ts")) } fn walk(root: &std::path::Path, dir: &std::path::Path, out: &mut Vec<(String, std::path::PathBuf)>) { diff --git a/apps/desktop/src/plugin_host/aux_windows/dispatch.rs b/apps/desktop/src/plugin_host/aux_windows/dispatch.rs index 7b503bfcc..5320fd6b3 100644 --- a/apps/desktop/src/plugin_host/aux_windows/dispatch.rs +++ b/apps/desktop/src/plugin_host/aux_windows/dispatch.rs @@ -1,30 +1,23 @@ -//! Auxiliary-window JS callback trampoline: routes UI event handlers (`onPress`, `onChange`, -//! `onHover`, `onMiddlePress`, `onSubmit`, `onScroll`, `onKey`, `onSelect`, `onContextMenu`, -//! `onVisibleRows`, pointer/key surface handlers, and virtualized `renderRow`) from a floating -//! auxiliary window back onto the owning parent window's `App` via `parent.update(...)` + -//! `cx::enter(parent_app)`, with zero overhead on main-window renders. +//! Auxiliary-window native UI callback routing via Rune's `Script::set_event_router`, +//! `Script::with_event_tag`, and owned deferrable [`RoutedEvent`]. +//! +//! Every callback built while rendering an auxiliary window (`onPress`, `onHover`, `onDrag`, +//! `onLink`, `onScroll`, `HostNode` handlers, `ui.virtualList` rows, and JSX `__rune_jsx` +//! elements) captures that window's unique `mailbox_key` tag. When fired from the floating +//! auxiliary display shell, the router defers the owned `RoutedEvent` onto the parent window's +//! `App` via `parent.update(...)` + `cx::enter(parent_app)`, with zero overhead on untagged +//! main-window renders. use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; -use opencode_plugin_runtime::js::{HostCtx, JsError, JsFn, JsObj, JsResult, JsVal, Key, Val}; use rune::{AppHandle, Tx}; -use rune_psychoscript::Script; +use rune_psychoscript::{EventRouter, RoutedEvent, Script}; use crate::App; use crate::plugin_host::{cx, requests}; -type WindowKey = (Rc, String); -type UiEntries = Rc>; - -struct DispatchedCall { - plugin_id: Rc, - vm_id: u64, - func: JsFn, - args: Vec, -} - #[derive(Clone)] struct AuxTarget { plugin_id: Rc, @@ -33,413 +26,67 @@ struct AuxTarget { parent: AppHandle, } -/// Explicit state machine tracking `@rune/ui` trampoline wrapping for a single VM. -#[derive(Default)] -enum WrapState { - #[default] - Unwrapped, - /// Non-empty stack of active render targets; the top frame is the current target. - Wrapped { frames: Vec> }, -} - -enum WrapEvent { - Enter(Option), - Exit, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum UiPatch { - None, - Wrap, - Unwrap, -} - -struct WrapEffects { - patch: UiPatch, - window_id: Option, -} - -impl WrapState { - fn active_target(&self) -> Option<&AuxTarget> { - match self { - Self::Unwrapped => None, - Self::Wrapped { frames } => frames.iter().rev().find_map(Option::as_ref), - } - } - - fn step(&mut self, event: WrapEvent) -> WrapEffects { - match (std::mem::take(self), event) { - (Self::Unwrapped, WrapEvent::Enter(target)) => { - let window_id = target.as_ref().map(|t| t.window_id.clone()); - *self = Self::Wrapped { frames: vec![target] }; - WrapEffects { patch: UiPatch::Wrap, window_id } - } - (Self::Wrapped { mut frames }, WrapEvent::Enter(target)) => { - let window_id = target.as_ref().map(|t| t.window_id.clone()); - frames.push(target); - *self = Self::Wrapped { frames }; - WrapEffects { patch: UiPatch::None, window_id } - } - (Self::Wrapped { mut frames }, WrapEvent::Exit) => { - frames.pop(); - if frames.is_empty() { - *self = Self::Unwrapped; - WrapEffects { patch: UiPatch::Unwrap, window_id: Some(String::new()) } - } else { - let window_id = frames - .iter() - .rev() - .find_map(Option::as_ref) - .map(|t| t.window_id.clone()) - .unwrap_or_default(); - *self = Self::Wrapped { frames }; - WrapEffects { patch: UiPatch::None, window_id: Some(window_id) } - } - } - (Self::Unwrapped, WrapEvent::Exit) => WrapEffects { patch: UiPatch::None, window_id: None }, - } - } -} - -/// Per-VM cached `@rune/ui` trampoline stored in `Session` user data so repeated auxiliary-window -/// renders allocate zero new JS wrappers, closures, or pins. -#[derive(Clone)] -struct AuxUiWrapCache { - ui: JsObj, - state: JsObj, - win_id_key: Key, - orig_entries: UiEntries, - wrapped_entries: UiEntries, - wrap: Rc>, - targets: Rc>>, +struct DeferredEvent { + vm_id: u64, + event: RoutedEvent, } thread_local! { - /// UI-thread queue of auxiliary-window JS callbacks waiting to execute on the parent `App`, - /// keyed by `(plugin_id, window_id)` so cached `view.Memo`/`ui.each` callbacks survive reopen. - static DISPATCH_QUEUE: RefCell>> = RefCell::new(HashMap::new()); + /// Active auxiliary-window targets keyed by unique `mailbox_key` (event tag). + static TARGETS: RefCell> = RefCell::new(HashMap::new()); + /// UI-thread queue of deferred `RoutedEvent`s waiting to execute on the parent `App`, + /// keyed by `mailbox_key` so multiple parent windows and reopens never collide. + static DISPATCH_QUEUE: RefCell>> = RefCell::new(HashMap::new()); + /// Shared process-wide `EventRouter` handle reused across all scripts with auxiliary windows. + static ROUTER: EventRouter = Rc::new(route_event); } -/// Drops any queued callbacks for a closed, reopened, or reaped auxiliary window. -pub(super) fn clear_dispatched(plugin_id: &str, window_id: &str) { - let key = (Rc::::from(plugin_id), window_id.to_owned()); - DISPATCH_QUEUE.with(|q| { - q.borrow_mut().remove(&key); - }); +fn shared_router() -> EventRouter { + ROUTER.with(Rc::clone) } -/// Psychoscript JS helper that constructs wrapped `@rune/ui` constructors once per VM, routing -/// every callback prop through `dispatch(winId, fn, ...args)` (capturing `state.windowId` at -/// wrap time) and every `renderRow` through the Rust state-guarded `wrapRow`. Skips non-node -/// helpers (`each`, `hex`) and forwards any number of arguments via JS rest parameters. -const WRAP_UI_JS: &str = r#" -return (function(ui, dispatch, wrapRow, state) { - const SKIP_KEYS = { - each: true, - hex: true, - }; - const CB_KEYS = { - onPress: true, - onMiddlePress: true, - onHover: true, - onDrag: true, - onLink: true, - onChange: true, - onSubmit: true, - onScroll: true, - onKey: true, - onSelect: true, - onContextMenu: true, - onDragStart: true, - onDragEnd: true, - onDragOver: true, - onDrop: true, - onResize: true, - onVisibleRows: true, - onPointerDown: true, - onPointerMove: true, - onPointerUp: true, - onKeyDown: true, - onKeyUp: true, - }; - function isPlainObj(v) { - return v !== null && typeof v === "object" && !Array.isArray(v); - } - function wrapProps(tbl) { - const keys = Object.keys(tbl); - let needs = false; - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if ((CB_KEYS[k] || k === "renderRow") && typeof tbl[k] === "function") { - needs = true; - break; - } - } - if (!needs) { - return tbl; - } - const winId = state.windowId; - const copy = {}; - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - const v = tbl[k]; - if (CB_KEYS[k] && typeof v === "function") { - const origCb = v; - copy[k] = function(...args) { - return dispatch(winId, origCb, ...args); - }; - } else if (k === "renderRow" && typeof v === "function") { - copy[k] = wrapRow(v); - } else { - copy[k] = v; - } - } - return copy; - } - const wrapped = {}; - const uiKeys = Object.keys(ui); - for (let i = 0; i < uiKeys.length; i++) { - const k = uiKeys[i]; - const orig = ui[k]; - if (typeof orig === "function" && !SKIP_KEYS[k]) { - wrapped[k] = function(...args) { - const n = args.length; - if (n === 0) { - return orig(); - } - let changed = false; - let out = null; - for (let j = 0; j < n; j++) { - const a = args[j]; - if (isPlainObj(a)) { - const w = wrapProps(a); - if (w !== a) { - if (!changed) { - out = args.slice(); - changed = true; - } - out[j] = w; - } - } - } - return changed ? orig(...out) : orig(...args); - }; - } - } - return wrapped; -}); -"#; - -fn get_ui_module(ctx: &mut HostCtx<'_>) -> Option { - let req = ctx.get_global("require")?; - let name = ctx.new_str("@rune/ui"); - let ui = ctx.call_fn_val(req, Val::UNDEFINED, &[name]).ok()?; - ctx.is_object(ui).then_some(ui) -} - -fn collect_fn_entries( - ctx: &mut HostCtx<'_>, - obj: Val, - skip: impl Fn(&str) -> bool, -) -> UiEntries { - let mut raw = Vec::new(); - ctx.obj_for_each(obj, |name, v| { - if ctx.is_fn(v) && !skip(name) { - raw.push((name.to_owned(), v)); - } +/// Drops any registered target and queued callbacks for a closed, reopened, or reaped auxiliary +/// window (`mailbox_key`). +pub(super) fn clear_dispatched(mailbox_key: u64) { + TARGETS.with(|t| { + t.borrow_mut().remove(&mailbox_key); + }); + DISPATCH_QUEUE.with(|q| { + q.borrow_mut().remove(&mailbox_key); }); - let mut pinned = Vec::with_capacity(raw.len()); - for (name, v) in raw { - if let Some(f) = JsFn::pin(ctx, v) { - pinned.push((name, f)); - } - } - Rc::new(pinned) -} - -fn apply_ui_entries(ctx: &mut HostCtx<'_>, ui: Val, entries: &[(String, JsFn)]) { - for (name, f) in entries { - let val = f.val(ctx); - ctx.obj_set_str(ui, name, val); - } -} - -fn apply_effects( - ctx: &mut HostCtx<'_>, - ui: &JsObj, - state: &JsObj, - win_id_key: Key, - orig: &UiEntries, - wrapped: &UiEntries, - effects: WrapEffects, -) { - if let Some(win_id) = effects.window_id { - let state_val = state.val(ctx); - let win_val = ctx.new_str(&win_id); - ctx.obj_set(state_val, win_id_key, win_val); - } - match effects.patch { - UiPatch::None => {} - UiPatch::Wrap => { - let ui_val = ui.val(ctx); - apply_ui_entries(ctx, ui_val, wrapped); - } - UiPatch::Unwrap => { - let ui_val = ui.val(ctx); - apply_ui_entries(ctx, ui_val, orig); - } - } -} - -fn apply_cache_effects(ctx: &mut HostCtx<'_>, cache: &AuxUiWrapCache, effects: WrapEffects) { - apply_effects( - ctx, - &cache.ui, - &cache.state, - cache.win_id_key, - &cache.orig_entries, - &cache.wrapped_entries, - effects, - ); -} - -struct WrapScope<'a, 'b> { - ctx: &'a mut HostCtx<'b>, - ui: &'a JsObj, - state: &'a JsObj, - win_id_key: Key, - orig: &'a UiEntries, - wrap: &'a RefCell, -} - -impl Drop for WrapScope<'_, '_> { - fn drop(&mut self) { - let effects = self.wrap.borrow_mut().step(WrapEvent::Exit); - apply_effects( - self.ctx, - self.ui, - self.state, - self.win_id_key, - self.orig, - self.orig, - effects, - ); - } } -fn get_or_build_cache(ctx: &mut HostCtx<'_>) -> JsResult> { - if let Some(cached) = ctx.get_user_data::() { - return Ok(Some(cached)); - } - let Some(ui) = get_ui_module(ctx) else { - return Ok(None); +fn route_event(tag: u64, event: RoutedEvent, tx: Option<&mut Tx>) -> bool { + let Some(target) = TARGETS.with(|t| t.borrow().get(&tag).cloned()) else { + return false; }; - let orig_entries = collect_fn_entries(ctx, ui, |name| matches!(name, "each" | "hex")); - let ui_obj = JsObj::pin(ctx, ui) - .ok_or_else(|| JsError::runtime("aux_windows: @rune/ui is not an object"))?; - - let state_val = ctx.new_object(1); - let win_id_key = ctx.key("windowId"); - let empty_str = ctx.new_str(""); - ctx.obj_set(state_val, win_id_key, empty_str); - let state_obj = JsObj::pin(ctx, state_val) - .ok_or_else(|| JsError::runtime("aux_windows: failed to pin trampoline state"))?; - - let wrap: Rc> = Rc::default(); - let targets: Rc>> = Rc::default(); - let wrapped_slot: Rc> = Rc::new(RefCell::new(Rc::new(Vec::new()))); - - let d_wrap = wrap.clone(); - let d_targets = targets.clone(); - let dispatch = ctx.new_local_fn("aux_windows.dispatch", move |ctx, args| { - let win_id = ctx.as_str(args.get(0)); - let Some(func) = JsFn::pin(ctx, args.get(1)) else { - return Ok(Val::UNDEFINED); - }; - let target = win_id - .as_deref() - .and_then(|id| d_targets.borrow().get(id).cloned()) - .or_else(|| d_wrap.borrow().active_target().cloned()); - let Some(target) = target else { - return Ok(Val::UNDEFINED); - }; - let mut rest = Vec::with_capacity(args.len().saturating_sub(2)); - for i in 2..args.len() { - if let Some(pinned) = JsVal::pin(ctx, args.get(i)) { - rest.push(pinned); - } - } - let queue_key = (target.plugin_id.clone(), target.window_id.clone()); - DISPATCH_QUEUE.with(|q| { - q.borrow_mut().entry(queue_key).or_default().push(DispatchedCall { - plugin_id: target.plugin_id.clone(), - vm_id: target.vm_id, - func, - args: rest, - }); - }); - let drain_p = target.plugin_id.to_string(); - let drain_w = target.window_id; - target.parent.update(move |parent_app: &mut App, tx: &mut Tx| { - drain_dispatched(parent_app, &drain_p, &drain_w, tx); + // Already running inside the owning parent window's `cx::enter` (e.g. `onScroll` delivered + // during `Script::poll` on the parent, or headless mode): execute synchronously. + let on_parent = cx::with_app(|app| !super::is_aux(app)).unwrap_or(false); + if on_parent { + return event.run(tx); + } + // Fired on the lightweight auxiliary display window: defer onto the owning parent `App`. + DISPATCH_QUEUE.with(|q| { + q.borrow_mut().entry(tag).or_default().push(DeferredEvent { + vm_id: target.vm_id, + event, }); - Ok(Val::UNDEFINED) }); - - let row_ui = ui_obj.clone(); - let row_state = state_obj.clone(); - let row_orig = orig_entries.clone(); - let row_wrapped = wrapped_slot.clone(); - let row_wrap = wrap.clone(); - let wrap_row = ctx.new_local_fn("aux_windows.wrapRow", move |ctx, args| { - let Some(orig_row) = JsFn::pin(ctx, args.get(0)) else { - return Err(ctx.type_error("renderRow must be a function")); - }; - let captured_target = row_wrap.borrow().active_target().cloned(); - let ui = row_ui.clone(); - let state = row_state.clone(); - let orig = row_orig.clone(); - let wrapped = row_wrapped.borrow().clone(); - let wrap = row_wrap.clone(); - let wrapped_row = ctx.new_local_fn("aux_windows.renderRow", move |ctx, args| { - let effects = wrap.borrow_mut().step(WrapEvent::Enter(captured_target.clone())); - apply_effects(ctx, &ui, &state, win_id_key, &orig, &wrapped, effects); - let scope = WrapScope { ctx, ui: &ui, state: &state, win_id_key, orig: &orig, wrap: &wrap }; - let call_args: Vec = (0..args.len()).map(|i| args.get(i)).collect(); - let orig_val = orig_row.val(scope.ctx); - let result = scope.ctx.call_fn_val(orig_val, Val::UNDEFINED, &call_args); - drop(scope); - result - }); - Ok(wrapped_row) + let drain_p = target.plugin_id.to_string(); + let drain_w = target.window_id; + target.parent.update(move |parent_app: &mut App, parent_tx: &mut Tx| { + drain_dispatched(parent_app, tag, &drain_p, &drain_w, parent_tx); }); - - let wrapped_tbl = opencode_plugin_runtime::chunk::eval_call( - ctx, - "=aux_windows.trampoline", - WRAP_UI_JS, - &[ui, dispatch, wrap_row, state_val], - )?; - let wrapped_entries = collect_fn_entries(ctx, wrapped_tbl, |_| false); - *wrapped_slot.borrow_mut() = wrapped_entries.clone(); - - let cache = AuxUiWrapCache { - ui: ui_obj, - state: state_obj, - win_id_key, - orig_entries, - wrapped_entries, - wrap, - targets, - }; - ctx.set_user_data(cache.clone()); - Ok(Some(cache)) + true } -/// Executes `f` while temporarily wrapping `@rune/ui` in `script` so all callback props built -/// during an auxiliary window render dispatch onto `parent_app` instead of the aux display shell. -pub(super) fn with_ui_trampoline( +/// Executes `f` with `script`'s native `EventRouter` attached and `mailbox_key` pushed as the +/// active event tag so every UI callback created during the auxiliary window render routes onto +/// `parent_app` instead of the aux display shell. +pub(super) fn with_event_routing( script: &Script, + mailbox_key: u64, plugin_id: Rc, window_id: String, vm_id: u64, @@ -449,71 +96,52 @@ pub(super) fn with_ui_trampoline( let Some(parent) = parent_app else { return f(); }; - let target = AuxTarget { plugin_id, window_id, vm_id, parent }; - let entered: Option = script - .with_ctx(|ctx| -> JsResult> { - let Some(cache) = get_or_build_cache(ctx)? else { - return Ok(None); - }; - cache.targets.borrow_mut().insert(target.window_id.clone(), target.clone()); - let effects = cache.wrap.borrow_mut().step(WrapEvent::Enter(Some(target))); - apply_cache_effects(ctx, &cache, effects); - Ok(Some(cache)) - }) - .and_then(Result::ok) - .flatten(); - - struct Restore<'a> { - script: &'a Script, - cache: Option, - } - impl Drop for Restore<'_> { - fn drop(&mut self) { - if let Some(cache) = self.cache.take() { - let effects = cache.wrap.borrow_mut().step(WrapEvent::Exit); - let _ = self.script.with_ctx(|ctx| apply_cache_effects(ctx, &cache, effects)); - } - } - } - let _guard = Restore { script, cache: entered }; - f() + TARGETS.with(|t| { + t.borrow_mut().insert( + mailbox_key, + AuxTarget { plugin_id, window_id, vm_id, parent }, + ); + }); + script.set_event_router(Some(shared_router())); + script.with_event_tag(mailbox_key, f) } -/// Executes queued auxiliary-window JS callbacks against the owning parent `App`. -pub(super) fn drain_dispatched(app: &mut App, plugin_id: &str, window_id: &str, tx: &mut Tx) { - let key = (Rc::::from(plugin_id), window_id.to_owned()); - let calls = DISPATCH_QUEUE.with(|q| q.borrow_mut().remove(&key).unwrap_or_default()); - if calls.is_empty() { +/// Executes queued auxiliary-window [`RoutedEvent`]s against the owning parent `App`. +fn drain_dispatched(app: &mut App, mailbox_key: u64, plugin_id: &str, window_id: &str, tx: &mut Tx) { + let events = DISPATCH_QUEUE.with(|q| q.borrow_mut().remove(&mailbox_key).unwrap_or_default()); + if events.is_empty() { return; } + let key = (Rc::::from(plugin_id), window_id.to_owned()); let mut ran = false; - for call in calls { - // Verify the auxiliary window is still open and owned by this plugin + VM. + for item in events { + // Verify the auxiliary window is still open at this exact `mailbox_key`, plugin, and VM. let live_window = app .kernel .slots .get(&super::AUX_MANAGER) .entries .get(&key) - .is_some_and(|e| e.vm_id == Some(call.vm_id) && e.phase.is_open()); + .is_some_and(|e| { + e.phase.mailbox_key() == Some(mailbox_key) + && e.vm_id == Some(item.vm_id) + && e.phase.is_open() + }); if !live_window { continue; } - let Some(i) = app.plugins.find(&call.plugin_id) else { + let Some(i) = app.plugins.find(plugin_id) else { continue; }; - let plugin = &app.plugins.list[i]; - let Some(script) = plugin.adopted_script() else { + let Some(script) = app.plugins.list[i].adopted_script() else { continue; }; - if script.vm_id() != Some(call.vm_id) { + if script.vm_id() != Some(item.vm_id) { continue; } - let call_args = call.args; - drop(cx::enter(app, || { - script.spawn_fn_with(&call.func, |ctx| call_args.iter().map(|v| v.val(ctx)).collect(), Some(&mut *tx)) - })); - ran = true; + if cx::enter(app, || item.event.run(Some(&mut *tx))) { + ran = true; + } } if ran { requests::carry_out(app, tx); diff --git a/apps/desktop/src/plugin_host/aux_windows/mod.rs b/apps/desktop/src/plugin_host/aux_windows/mod.rs index 535411777..5f00cca3f 100644 --- a/apps/desktop/src/plugin_host/aux_windows/mod.rs +++ b/apps/desktop/src/plugin_host/aux_windows/mod.rs @@ -309,7 +309,7 @@ fn run_effects(app: &mut App, plugin: &str, id: &str, effects: Vec { clear_embed_aux_wakers(app, plugin, id); host::clear_mailbox(mailbox_key); - dispatch::clear_dispatched(plugin, id); + dispatch::clear_dispatched(mailbox_key); let handles = app .kernel .slots @@ -329,6 +329,7 @@ fn run_effects(app: &mut App, plugin: &str, id: &str, effects: Vec { host::clear_mailbox(mailbox_key); + dispatch::clear_dispatched(mailbox_key); let (captured_cb, is_closed) = app .kernel .slots @@ -346,7 +347,6 @@ fn run_effects(app: &mut App, plugin: &str, id: &str, effects: Vec bool { let Some(script) = app.plugins.list[i].adopted_script() else { return rune::el(); }; - dispatch::with_ui_trampoline(script, Rc::from(plugin), id.to_owned(), vm_id, parent_handle, || { - surfaces::render(app, &p, i, &surface_key, &render_fn, props) - }) + dispatch::with_event_routing( + script, + mailbox_key, + Rc::from(plugin), + id.to_owned(), + vm_id, + parent_handle, + || surfaces::render(app, &p, i, &surface_key, &render_fn, props), + ) }); let generation = { let mgr = app.kernel.slots.get_mut(&AUX_MANAGER); @@ -706,10 +712,10 @@ pub fn reap_plugin(app: &mut App, plugin_id: &str, keep_vm: Option) { } for key in gone { clear_embed_aux_wakers(app, &key.0, &key.1); - dispatch::clear_dispatched(&key.0, &key.1); if let Some(mut entry) = app.kernel.slots.get_mut(&AUX_MANAGER).entries.remove(&key) { if let Some(mkey) = entry.phase.mailbox_key() { host::clear_mailbox(mkey); + dispatch::clear_dispatched(mkey); } if let Some(app_h) = entry.app_handle.take() { app_h.close(); @@ -726,9 +732,9 @@ pub fn close_all(app: &mut App) { let entries = std::mem::take(&mut app.kernel.slots.get_mut(&AUX_MANAGER).entries); for ((plugin, id), mut entry) in entries { clear_embed_aux_wakers(app, &plugin, &id); - dispatch::clear_dispatched(&plugin, &id); if let Some(mkey) = entry.phase.mailbox_key() { host::clear_mailbox(mkey); + dispatch::clear_dispatched(mkey); } if let Some(app_h) = entry.app_handle.take() { app_h.close(); diff --git a/apps/desktop/src/plugin_host/runtime/hot.rs b/apps/desktop/src/plugin_host/runtime/hot.rs index b0f61e124..216def78f 100644 --- a/apps/desktop/src/plugin_host/runtime/hot.rs +++ b/apps/desktop/src/plugin_host/runtime/hot.rs @@ -4,7 +4,7 @@ pub use opencode_plugin_runtime::hot::{Prepared, Watcher, prepare}; use std::path::PathBuf; -/// Watches `dirs` (plugin index, folder) for `.js`, `.ts`, `.toml`, `.json`, and `.svg` saves. +/// Watches `dirs` (plugin index, folder) for `.js`, `.jsx`, `.ts`, `.tsx`, `.toml`, `.json`, and `.svg` saves. pub fn spawn(dirs: Vec<(usize, PathBuf)>, waker: Option) -> Option { Watcher::spawn(dirs, waker) } diff --git a/crates/opencode-plugin-runtime/src/console.rs b/crates/opencode-plugin-runtime/src/console.rs index af80efcc5..509de47d8 100644 --- a/crates/opencode-plugin-runtime/src/console.rs +++ b/crates/opencode-plugin-runtime/src/console.rs @@ -17,7 +17,7 @@ pub struct Line { pub plugin: String, pub level: LogLevel, pub message: String, - /// `file.js:line` or `file.ts:line` from the message, if it names one. + /// `file.{js,jsx,ts,tsx}:line` from the message, if it names one. pub at: Option<(String, u32)>, pub count: u32, } @@ -127,20 +127,20 @@ pub fn clear_for(plugin: &str) { } } -/// The first `name.js:line` or `name.ts:line` in a message. +/// The first `name.{js,jsx,ts,tsx}:line` in a message. fn location(message: &str) -> Option<(String, u32)> { - let at = [message.find(".js:"), message.find(".ts:")] + let (at, suffix_len) = [".js:", ".jsx:", ".ts:", ".tsx:"] .into_iter() - .flatten() - .min()?; + .filter_map(|suffix| message.find(suffix).map(|pos| (pos, suffix.len()))) + .min_by_key(|&(pos, _)| pos)?; let start = message[..at] .rfind(|c: char| c.is_whitespace() || c == '[' || c == '"' || c == '@' || c == '(') .map_or(0, |i| i + 1); - let digits: String = message[at + 4..] + let digits: String = message[at + suffix_len..] .chars() .take_while(char::is_ascii_digit) .collect(); - Some((message[start..at + 3].to_owned(), digits.parse().ok()?)) + Some((message[start..at + suffix_len - 1].to_owned(), digits.parse().ok()?)) } /// Every line as `ConsoleLine` records, oldest first. `resolve_dir` returns a plugin's folder on diff --git a/crates/opencode-plugin-runtime/src/hot.rs b/crates/opencode-plugin-runtime/src/hot.rs index be80550b7..0703b6f93 100644 --- a/crates/opencode-plugin-runtime/src/hot.rs +++ b/crates/opencode-plugin-runtime/src/hot.rs @@ -1,4 +1,4 @@ -//! Save-to-reload: a watcher over every PsychoScript plugin folder (`.js`, `.ts`, `.toml`, +//! Save-to-reload: a watcher over every PsychoScript plugin folder (`.js`, `.jsx`, `.ts`, `.tsx`, `.toml`, //! `.json`, `.svg`). Its thread rereads the files a save changed and validates/compiles the modules among //! them off the UI thread; meanwhile the UI thread builds the next VM's base (`Script::prewarm`), //! and the poll after the compile only swaps the VM. @@ -49,7 +49,7 @@ pub struct Watcher { } impl Watcher { - /// Watches `dirs` (plugin index, folder) for `.js`, `.ts`, `.toml`, `.json`, and `.svg` saves. + /// Watches `dirs` (plugin index, folder) for `.js`, `.jsx`, `.ts`, `.tsx`, `.toml`, `.json`, and `.svg` saves. pub fn spawn(dirs: Vec<(usize, PathBuf)>, waker: Option) -> Option { #[cfg(target_arch = "wasm32")] { diff --git a/crates/opencode-plugin-runtime/src/sources.rs b/crates/opencode-plugin-runtime/src/sources.rs index 21c2002f2..ba602e835 100644 --- a/crates/opencode-plugin-runtime/src/sources.rs +++ b/crates/opencode-plugin-runtime/src/sources.rs @@ -191,7 +191,7 @@ fn unreachable_manifest() -> Manifest { } impl Origin { - /// Assembles [`rune_psychoscript::Sources`] for the half starting at `entry` (default `init.js` or `init.ts`). + /// Assembles [`rune_psychoscript::Sources`] for the half starting at `entry` (default `init.js`, `init.ts`, `init.tsx`, or `init.jsx`). pub fn scripts( &self, files: &[(String, String)], @@ -276,14 +276,18 @@ pub fn relative(root: &Path, path: &Path) -> Option { Some(rel.join("/")) } -/// Whether `path` is a runnable JavaScript or TypeScript module (skipping `.d.ts` declarations). +/// Whether `path` is a runnable JavaScript, JSX, TypeScript, or TSX module (skipping `.d.ts` +/// declarations). pub fn is_script(path: &str) -> bool { - path.ends_with(".js") || (path.ends_with(".ts") && !path.ends_with(".d.ts")) + path.ends_with(".js") + || path.ends_with(".jsx") + || path.ends_with(".tsx") + || (path.ends_with(".ts") && !path.ends_with(".d.ts")) } -/// Whether a plugin runs from the file at `rel`: its manifest, JS/TS modules (`.js`, `.ts`, -/// excluding `.d.ts`), JSON data and `locales/*.json` catalogs (plus `locales/fill/*.json`, see -/// [`Catalogs`]), and `icons/*.svg` icons, outside hidden folders. +/// Whether a plugin runs from the file at `rel`: its manifest, JS/JSX/TS/TSX modules (`.js`, +/// `.jsx`, `.ts`, `.tsx`, excluding `.d.ts`), JSON data and `locales/*.json` catalogs (plus +/// `locales/fill/*.json`, see [`Catalogs`]), and `icons/*.svg` icons, outside hidden folders. pub fn kept(rel: &str) -> bool { let mut parts: Vec<&str> = rel.split('/').collect(); let Some(name) = parts.pop() else { @@ -313,34 +317,37 @@ pub fn intern_icons(plugin: &str, files: &[(String, String)]) -> Vec<(String, St } /// The script sources of the half that starts at `entry` (defaults to `init.js`, falling back -/// to `init.ts` when `init.js` is absent). +/// to `init.ts` -> `init.tsx` -> `init.jsx` when `init.js` is absent). pub fn script_sources( files: &[(String, String)], folder: &str, entry: &str, ) -> rune_psychoscript::Sources { + const DEFAULT_ENTRIES: [&str; 4] = [ + rune_psychoscript::ENTRY, + rune_psychoscript::ENTRY_TS, + rune_psychoscript::ENTRY_TSX, + rune_psychoscript::ENTRY_JSX, + ]; let has = |p: &str| files.iter().any(|(path, _)| path == p); - let entry = if entry.is_empty() - || (entry == rune_psychoscript::ENTRY && !has(entry) && has(rune_psychoscript::ENTRY_TS)) - { - if has(rune_psychoscript::ENTRY) { - rune_psychoscript::ENTRY - } else if has(rune_psychoscript::ENTRY_TS) { - rune_psychoscript::ENTRY_TS - } else { - rune_psychoscript::ENTRY - } + let entry = if entry.is_empty() || (entry == rune_psychoscript::ENTRY && !has(entry)) { + DEFAULT_ENTRIES + .iter() + .copied() + .find(|candidate| has(candidate)) + .unwrap_or(rune_psychoscript::ENTRY) } else { entry }; - let entry_is_ts = entry.ends_with(".ts") && !entry.ends_with(".d.ts"); + let entry_is_ts = + entry.ends_with(".tsx") || (entry.ends_with(".ts") && !entry.ends_with(".d.ts")); files .iter() .filter(|(p, _)| { if entry_is_ts { is_script(p) || p.ends_with(".json") } else { - p.ends_with(".js") || p.ends_with(".json") + p.ends_with(".js") || p.ends_with(".jsx") || p.ends_with(".json") } }) .fold(rune_psychoscript::Sources::new(), |s, (p, text)| { diff --git a/crates/opencode-plugin-spec/src/codegen/ts.rs b/crates/opencode-plugin-spec/src/codegen/ts.rs index bf53332ad..59427d2a6 100644 --- a/crates/opencode-plugin-spec/src/codegen/ts.rs +++ b/crates/opencode-plugin-spec/src/codegen/ts.rs @@ -87,6 +87,10 @@ pub fn definitions(c: &Contract) -> Result { for m in &c.ui_extras { member(&mut o, m, false)?; } + jsdoc(&mut o, 1, "JSX element factory (`__rune_jsx`): creates a UI node or invokes a function component.", None, None); + o.line(" h: typeof __rune_jsx;"); + jsdoc(&mut o, 1, "JSX Fragment sentinel (`__rune_frag`, used by `<>...`).", None, None); + o.line(" readonly Fragment: typeof __rune_frag;"); o.line("}"); o.blank(); @@ -192,6 +196,29 @@ pub fn definitions(c: &Contract) -> Result { o.line(" new (): AbortController;"); o.line("};"); o.blank(); + o.line("/** JSX Fragment sentinel (`<>...`). */"); + o.line("declare const __rune_frag: unique symbol;"); + o.line("/** JSX element factory lowered automatically from `.tsx` and `.jsx` files. */"); + o.line("declare function __rune_jsx("); + o.line(" tag: string | typeof __rune_frag | ((props: any) => any),"); + o.line(" props?: Record | null,"); + o.line(" ...children: any[]"); + o.line("): UiNode;"); + o.blank(); + o.line("/** Ambient JSX type definitions for zero-build `.tsx` and `.jsx` PsychoScript plugins. */"); + o.line("declare namespace JSX {"); + o.line(" type Element = UiNode;"); + o.line(" interface ElementChildrenAttribute {"); + o.line(" children: {};"); + o.line(" }"); + o.line(" interface IntrinsicElements {"); + for n in &c.nodes { + o.line(&format!(" {}: {} & {{ children?: any }};", n.name, n.props)); + } + o.line(" [name: string]: any;"); + o.line(" }"); + o.line("}"); + o.blank(); o.line("/** CommonJS module object for plugin entrypoints and local modules. */"); o.line("declare var module: { exports: any };"); o.line("declare var exports: any;"); @@ -405,6 +432,9 @@ pub fn tsconfig() -> String { "target": "ES2022", "module": "Preserve", "moduleResolution": "Bundler", + "jsx": "react", + "jsxFactory": "__rune_jsx", + "jsxFragmentFactory": "__rune_frag", "allowJs": true, "checkJs": false, "noEmit": true, @@ -417,8 +447,12 @@ pub fn tsconfig() -> String { "types/**/*.d.ts", "*/*.js", "*/*/*.js", + "*/*.jsx", + "*/*/*.jsx", "*/*.ts", - "*/*/*.ts" + "*/*/*.ts", + "*/*.tsx", + "*/*/*.tsx" ] } "# diff --git a/plugins/opencode.d.ts b/plugins/opencode.d.ts index 89cec36fd..e5ffafa3a 100644 --- a/plugins/opencode.d.ts +++ b/plugins/opencode.d.ts @@ -11036,6 +11036,10 @@ interface UiLibrary { hex(color: string): HexColor; /** A node for each item, as children to pass on: `build(item, index)`, memoized per item as `view.Memo` is, by its key and version. A render builds again only the items whose version changed. `key` and `version` are field names (`"id"`) or functions of the item. An item's key becomes its node's key, so keep keys unique in the render. Put everything the row draws with, the theme among it, in its version. */ each(items: T[], key: string | ((item: T, index: number) => string | number), version: string | ((item: T, index: number) => MemoVersion), build: (item: T, index: number) => UiNode): UiNode[]; + /** JSX element factory (`__rune_jsx`): creates a UI node or invokes a function component. */ + h: typeof __rune_jsx; + /** JSX Fragment sentinel (`__rune_frag`, used by `<>...`). */ + readonly Fragment: typeof __rune_frag; } /** `require("@opencode/plugin")`: defines a plugin's halves. */ @@ -11133,6 +11137,79 @@ declare var AbortController: { new (): AbortController; }; +/** JSX Fragment sentinel (`<>...`). */ +declare const __rune_frag: unique symbol; +/** JSX element factory lowered automatically from `.tsx` and `.jsx` files. */ +declare function __rune_jsx( + tag: string | typeof __rune_frag | ((props: any) => any), + props?: Record | null, + ...children: any[] +): UiNode; + +/** Ambient JSX type definitions for zero-build `.tsx` and `.jsx` PsychoScript plugins. */ +declare namespace JSX { + type Element = UiNode; + interface ElementChildrenAttribute { + children: {}; + } + interface IntrinsicElements { + box: UiBoxProps & { children?: any }; + row: UiBoxProps & { children?: any }; + col: UiBoxProps & { children?: any }; + frame: UiFrameProps & { children?: any }; + spacer: UiSpacerProps & { children?: any }; + divider: UiDividerProps & { children?: any }; + text: UiTextProps & { children?: any }; + rich: UiTextProps & { children?: any }; + icon: UiIconProps & { children?: any }; + image: UiImageProps & { children?: any }; + video: UiVideoProps & { children?: any }; + surface: UiSurfaceProps & { children?: any }; + metric: UiMetricProps & { children?: any }; + shimmer: UiTextProps & { children?: any }; + keybind: UiKeybindProps & { children?: any }; + button: UiButtonProps & { children?: any }; + iconButton: UiIconButtonProps & { children?: any }; + switch: UiSwitchProps & { children?: any }; + checkbox: UiCheckboxProps & { children?: any }; + radio: UiRadioProps & { children?: any }; + field: UiFieldProps & { children?: any }; + listbox: UiListboxProps & { children?: any }; + option: UiOptionProps & { children?: any }; + select: UiSelectProps & { children?: any }; + segmented: UiSegmentedProps & { children?: any }; + loader: UiLoaderProps & { children?: any }; + progressCircle: UiProgressCircleProps & { children?: any }; + serverIndicator: UiServerIndicatorProps & { children?: any }; + pill: UiPillProps & { children?: any }; + badge: UiBadgeProps & { children?: any }; + settingsRow: UiSettingsRowProps & { children?: any }; + settingsList: UiSettingsListProps & { children?: any }; + flyoutRow: UiFlyoutRowProps & { children?: any }; + dialogHeader: UiDialogHeaderProps & { children?: any }; + tooltip: UiTooltipProps & { children?: any }; + dragItem: UiDragItemProps & { children?: any }; + dropZone: UiDropZoneProps & { children?: any }; + splitPane: UiSplitPaneProps & { children?: any }; + code: UiCodeProps & { children?: any }; + markdown: UiMarkdownProps & { children?: any }; + virtualList: UiVirtualListProps & { children?: any }; + terminalSurface: UiTerminalSurfaceProps & { children?: any }; + terminalTabLabel: UiTerminalTabLabelProps & { children?: any }; + browserSurface: UiBrowserSurfaceProps & { children?: any }; + codeView: UiCodeViewProps & { children?: any }; + diffView: UiDiffViewProps & { children?: any }; + fileTree: UiFileTreeProps & { children?: any }; + panelSidebar: UiPanelSidebarProps & { children?: any }; + openInButton: UiOpenInButtonProps & { children?: any }; + officePages: UiOfficePagesProps & { children?: any }; + officeSheet: UiOfficeSheetProps & { children?: any }; + genUi: UiGenUiProps & { children?: any }; + embed: UiEmbedProps & { children?: any }; + [name: string]: any; + } +} + /** CommonJS module object for plugin entrypoints and local modules. */ declare var module: { exports: any }; declare var exports: any; diff --git a/plugins/tsconfig.json b/plugins/tsconfig.json index 096287ed6..10aca87d4 100644 --- a/plugins/tsconfig.json +++ b/plugins/tsconfig.json @@ -3,6 +3,9 @@ "target": "ES2022", "module": "Preserve", "moduleResolution": "Bundler", + "jsx": "react", + "jsxFactory": "__rune_jsx", + "jsxFragmentFactory": "__rune_frag", "allowJs": true, "checkJs": false, "noEmit": true, @@ -15,7 +18,11 @@ "types/**/*.d.ts", "*/*.js", "*/*/*.js", + "*/*.jsx", + "*/*/*.jsx", "*/*.ts", - "*/*/*.ts" + "*/*/*.ts", + "*/*.tsx", + "*/*/*.tsx" ] } diff --git a/scripts/new-plugin.mjs b/scripts/new-plugin.mjs index d3718218a..22bf0fdf7 100755 --- a/scripts/new-plugin.mjs +++ b/scripts/new-plugin.mjs @@ -3,7 +3,7 @@ // Runs on Bun or Node.js >= 18. // // Usage: -// bun scripts/new-plugin.mjs [--ts|--js] [--dir ] [--force] +// bun scripts/new-plugin.mjs [--ts|--tsx|--js] [--dir ] [--force] import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; @@ -48,10 +48,11 @@ function listBuiltinIds() { function usage() { return [ "Usage:", - " bun scripts/new-plugin.mjs [--ts|--js] [--dir ] [--force]", + " bun scripts/new-plugin.mjs [--ts|--tsx|--js] [--dir ] [--force]", "", "Options:", " --ts Generate a TypeScript plugin (init.ts, default)", + " --tsx Generate a zero-build TypeScript + JSX plugin (init.tsx)", " --js Generate a JavaScript plugin (init.js)", " --dir Parent directory to create / in (default: ./local-plugins)", " --force Overwrite an existing plugin directory or shadow a built-in plugin id", @@ -59,6 +60,7 @@ function usage() { "", "Examples:", " bun scripts/new-plugin.mjs hello-demo", + " bun scripts/new-plugin.mjs hello-demo --tsx --dir ./my-plugins", " bun scripts/new-plugin.mjs hello-demo --ts --dir ./my-plugins", " bun scripts/new-plugin.mjs quick-note --js", ].join("\n"); @@ -77,6 +79,8 @@ function parseArgs(argv) { help = true; } else if (arg === "--ts") { lang = "ts"; + } else if (arg === "--tsx") { + lang = "tsx"; } else if (arg === "--js") { lang = "js"; } else if (arg === "--force") { @@ -384,24 +388,189 @@ export default plugin.defineWindow((ctx) => { `; } +function makeInitTsx(id, title) { + return `import plugin from "@opencode/plugin"; + +interface PluginState { + clicks: number; + status: "Ready" | "Working…"; +} + +interface StatBadgeProps { + label: string; + value: string; + tone?: Tone; +} + +function StatBadge({ label, value, tone = "accent" }: StatBadgeProps): UiNode { + const accent: Color = + tone === "success" + ? "status-success" + : tone === "warning" + ? "status-warning" + : tone === "danger" + ? "status-danger" + : "text-interactive"; + return ( + + + {label} + + + {value} + + + ); +} + +export default plugin.defineWindow((ctx) => { + const { Layout, Toast } = ctx.services; + const changed = ctx.CreateSignal(); + const state: PluginState = { + clicks: 0, + status: "Ready", + }; + + let resetTimer: number | null = null; + + // Clean up pending timers automatically on hot reload or teardown. + task.signal.addEventListener( + "abort", + () => { + if (resetTimer !== null) { + clearTimeout(resetTimer); + resetTimer = null; + } + }, + { once: true }, + ); + + function triggerPing(): void { + state.clicks += 1; + state.status = "Working…"; + changed.Fire(); + + if (resetTimer !== null) { + clearTimeout(resetTimer); + } + resetTimer = setTimeout(() => { + resetTimer = null; + if (task.signal.aborted) { + return; + } + state.status = "Ready"; + changed.Fire(); + Toast.Success(${JSON.stringify(title)}, \`Completed ping #\${state.clicks}\`); + }, 350); + } + + ctx.AddCommand({ + id: "open", + title: ${JSON.stringify(`Open ${title}`)}, + description: ${JSON.stringify(`Opens the ${title} panel and shows a toast`)}, + group: ${JSON.stringify(title)}, + requiresSession: true, + run: () => { + Layout.OpenPanel("main"); + Toast.Info(${JSON.stringify(title)}, "Panel opened"); + }, + }); + + ctx.AddPanel({ + id: "main", + title: ${JSON.stringify(title)}, + description: ${JSON.stringify(`Starter TSX panel for ${id}`)}, + icon: "code", + render: (view) => + view.Memo(\`panel-body\`, \`\${state.clicks}:\${state.status}\`, () => ( + + + + code + + + ${title} + + + + + + + + + {"Plugin "} + {{ text: ${JSON.stringify(id)}, mono: true, color: "text-interactive" }} + {" renders native zero-build JSX directly into Rune elements."} + + +