app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
[package]
name = "luau-panel"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish = false
[lib]
crate-type = ["cdylib", "rlib"]
[[bin]]
name = "luau-panel"
path = "src/main.rs"
[[bin]]
name = "luau-bench"
path = "src/bin/bench.rs"
[dependencies]
rune = { workspace = true, default-features = true, features = ["keys-overlay"] }
serde = { workspace = true, features = ["derive"] }
rune-luau = { workspace = true, features = ["serde"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rune-luau = { workspace = true, features = ["serde", "watch"] }
# The bench compares Luau's interpreter with its native code, which this example turns on where
# Luau has it.
[target.'cfg(all(any(target_os = "windows", target_os = "linux"), any(target_arch = "x86_64", target_arch = "aarch64")))'.dependencies]
rune-luau = { workspace = true, features = ["serde", "watch", "native-code"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = { workspace = true }
[lints]
workspace = true
+11
View File
@@ -0,0 +1,11 @@
{"events": [
{"t": 0.60, "type": "tap", "key": "pulse"},
{"t": 1.60, "type": "tap", "key": "ping"},
{"t": 2.20, "type": "tap", "x": 300, "y": 230},
{"t": 2.80, "type": "scroll", "x": 360, "y": 400, "dy": -1800, "dur": 1.2},
{"t": 4.40, "type": "tap", "x": 300, "y": 330},
{"t": 5.00, "type": "tap", "key": "shuffle"},
{"t": 5.60, "type": "scroll", "x": 360, "y": 400, "dy": -9000, "dur": 1.0},
{"t": 7.20, "type": "scroll", "x": 360, "y": 400, "dy": 12000, "dur": 1.2},
{"t": 9.00, "type": "mark", "name": "end"}
]}
@@ -0,0 +1,134 @@
--!strict
-- A panel a Rune app hosts: a header that counts presses, a pulse driven by task.wait, a
-- signal, and a 1,000-row virtual list. Edit this file while the app runs: it reloads in place
-- and keeps the selection and counters (saveHotState / loadHotState).
local ui = require("@rune/ui")
local rows = require("@self/rows")
local state = {
selected = 0,
presses = 0,
pulse = 0,
pings = 0,
shuffles = 0,
}
local items = rows.items(1000)
local listVersion = 0
local headerVersion = 0
local pulsing: thread? = nil
local pinged = require("@rune/signal").new()
local function changed(list: boolean)
headerVersion += 1
if list then
listVersion += 1
end
end
pinged:Connect(function(n: number)
state.pings = n
changed(false)
end)
local function select(i: number)
state.selected = i
state.presses += 1
changed(true)
end
local function pulse()
if pulsing then
task.cancel(pulsing)
end
pulsing = task.spawn(function()
for step = 10, 0, -1 do
state.pulse = step
changed(false)
task.wait(0.08)
end
pulsing = nil
end)
end
local function button(key: string, label: string, onPress: () -> ())
return ui.row({
key = key,
px = 10,
py = 4,
radius = 6,
fill = "control-off",
hover = "hover",
press = "press",
onPress = onPress,
}, { ui.text(label, { size = 12, weight = "medium" }) })
end
local function header()
local selected = if state.selected > 0 then `#{state.selected}` else "none"
return ui.col({ key = "header", w = "full", px = 16, pt = 14, pb = 10, gap = 8 }, {
ui.row({ w = "full", gap = 8, align = "center" }, {
ui.text("Luau panel", { size = 15, weight = "semibold" }),
ui.spacer(),
ui.text(`{#items} rows · selected {selected} · {state.presses} presses`, { size = 12, color = "text-secondary" }),
}),
ui.row({ w = "full", gap = 6, align = "center" }, {
button("shuffle", "Shuffle", function()
state.shuffles += 1
rows.shuffle(items, state.shuffles)
changed(true)
end),
button("pulse", "Pulse", pulse),
button("ping", "Ping", function()
pinged:Fire(state.pings + 1)
end),
ui.spacer(),
ui.box({ w = 120, h = 6, radius = 3, fill = "separator" }, {
ui.box({ w = state.pulse * 12, h = 6, radius = 3, fill = ui.hex("#009fff") }),
}),
ui.text(`{state.pings} pings`, { size = 12, color = "text-secondary", w = 60 }),
}),
})
end
local function render(view)
return ui.col({ key = "panel", w = "full", h = "full", fill = "bg" }, {
view:Memo("header", headerVersion, header),
ui.box({ w = "full", h = 1, fill = "separator" }),
ui.virtualList({
key = "items",
w = "full",
grow = 1,
count = #items,
estimatedRowHeight = 28,
version = listVersion,
renderRow = function(i: number)
return rows.row(items[i], i == state.selected, function()
select(i)
end)
end,
}),
})
end
return {
render = render,
-- For the host: select a row, and read the selection.
select = select,
selected = function()
return state.selected
end,
-- A 20-row stateful panel: the rebuild the performance gate measures.
panel20 = function(view)
return rows.panel20(state.presses)
end,
saveHotState = function()
return state
end,
loadHotState = function(saved)
for k, v in saved do
state[k] = v
end
rows.shuffle(items, state.shuffles)
end,
}
@@ -0,0 +1,75 @@
--!strict
local ui = require("@rune/ui")
export type Item = { id: number, name: string, size: number, done: boolean }
local NAMES = { "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet" }
local function items(n: number): { Item }
local out = table.create(n)
for i = 1, n do
out[i] = { id = i, name = `{NAMES[(i - 1) % #NAMES + 1]} {i}`, size = (i * 7919) % 1000, done = i % 3 == 0 }
end
return out
end
-- Reorders sizes deterministically for round `seed`.
local function shuffle(list: { Item }, seed: number)
for i, item in list do
item.size = (i * 7919 + seed * 104729) % 1000
end
end
local function row(item: Item, selected: boolean, onPress: () -> ())
return ui.row({
key = item.id,
w = "full",
h = 28,
px = 16,
gap = 10,
align = "center",
fill = if selected then "control-off" else nil,
hover = "hover",
onPress = onPress,
}, {
ui.text(`#{item.id}`, { size = 11, mono = true, color = "text-secondary", w = 44 }),
ui.text(item.name, { size = 13, grow = 1, truncate = true }),
ui.box({ w = 100, h = 4, radius = 2, fill = "separator" }, {
ui.box({ w = item.size / 10, h = 4, radius = 2, fill = ui.hex("#009fff") }),
}),
ui.text(if item.done then "done" else "open", {
size = 11,
color = if item.done then ui.hex("#30a46c") else "text-secondary",
w = 36,
}),
})
end
local LABELS = {
"Session", "Messages", "Provider", "Model", "Context limit", "Total tokens", "Usage", "Input tokens",
"Output tokens", "Reasoning tokens", "Cache read", "Cache write", "User messages", "Assistant messages",
"Total cost", "Created", "Last activity", "System prompt", "Tools", "Files",
}
-- Twenty label/value/bar rows, values computed per build as a stats tab's would be.
local function panel20(seed: number)
local out = table.create(20)
for i = 1, 20 do
local value = (i * 7919 + seed * 31) % 100000
out[i] = ui.row({ key = i, w = "full", h = 24, px = 16, gap = 8, align = "center" }, {
ui.text(LABELS[i], { size = 12, color = "text-secondary", w = 140 }),
ui.text(`{value // 1000},{string.format("%03d", value % 1000)}`, { size = 12, grow = 1, mono = true }),
ui.box({ w = 80, h = 4, radius = 2, fill = "separator" }, {
ui.box({ w = (value % 100) * 0.8, h = 4, radius = 2, fill = ui.hex("#009fff") }),
}),
})
end
return ui.col({ key = "panel20", w = "full", py = 8 }, out)
end
return {
items = items,
shuffle = shuffle,
row = row,
panel20 = panel20,
}
+272
View File
@@ -0,0 +1,272 @@
//! The Luau performance gates, measured on this panel in a headless `Runtime`: the same code
//! natively (`luau-bench`) and in the browser (`luau_bench()`).
use std::fmt;
use std::time::Duration;
use rune::time::now;
use rune::{Env, Runtime};
use rune_luau::{Data, Script, Sources};
use crate::{State, sources, view};
/// Iteration counts: the web gets fewer, and reports means over them (browsers coarsen timers).
#[derive(Clone, Copy, PartialEq)]
pub enum Scale {
Native,
Web,
}
/// Microseconds.
#[derive(Clone, Copy, Default)]
pub struct Stat {
pub n: usize,
pub mean: f64,
pub p50: f64,
pub p99: f64,
pub max: f64,
}
impl Stat {
fn of(mut samples: Vec<f64>) -> Stat {
if samples.is_empty() {
return Stat::default();
}
samples.sort_by(f64::total_cmp);
let n = samples.len();
let at = |q: f64| samples[((n - 1) as f64 * q).round() as usize];
Stat { n, mean: samples.iter().sum::<f64>() / n as f64, p50: at(0.5), p99: at(0.99), max: samples[n - 1] }
}
fn json(&self) -> String {
format!(r#"{{"n":{},"mean_us":{:.3},"p50_us":{:.3},"p99_us":{:.3},"max_us":{:.3}}}"#, self.n, self.mean, self.p50, self.p99, self.max)
}
}
pub struct Report {
pub native_code: bool,
/// Idle frames polled, frames any of them asked for, and VM entries they made.
pub idle: (usize, usize, u64),
/// `Script::view` on a view rebuilt by host state only, and the VM entries those calls made.
pub memo_hit: (Stat, u64),
/// Wall time, and the time the thread ran (Windows).
pub rebuild20: (Stat, Option<Stat>),
/// Script time per 120 fps scroll frame, whole frame time, rows `renderRow` built.
pub scroll: (Stat, Stat, u64),
/// Compile + swap, compile, swap; whether hot state survived every reload.
pub reload: (Stat, Stat, Stat, bool),
pub checks: Vec<crate::checks::Check>,
}
const SIZE: (f32, f32) = (720.0, 640.0);
const DT: f64 = 1.0 / 120.0;
fn us(d: Duration) -> f64 {
d.as_secs_f64() * 1e6
}
pub fn run(scale: Scale) -> Report {
let n = if scale == Scale::Web { 300 } else { 1000 };
Report {
native_code: rune_luau::NATIVE_CODE,
idle: idle(),
memo_hit: memo_hit(n),
rebuild20: rebuild20(n),
scroll: scroll(),
reload: reload(if scale == Scale::Web { 10 } else { 20 }),
checks: crate::checks::run(),
}
}
/// A runtime showing the panel, polled and framed until nothing is left to do.
fn runtime() -> (Runtime<State>, f64) {
let mut rt = Runtime::new(State::new(Script::new("panel", sources())), view, SIZE, Env::new(true, 1.0));
let mut now = 0.0;
rt.frame(0.0);
for _ in 0..600 {
now += DT;
let stale = rt.update_if(|s, tx| s.script.poll(now, tx));
if !rt.frame(DT) && !stale {
break;
}
}
(rt, now)
}
fn idle() -> (usize, usize, u64) {
let (mut rt, mut now) = runtime();
let before = rt.state.script.metrics().vm_calls;
let frames = 1200;
let mut asked = 0;
for _ in 0..frames {
now += DT;
let stale = rt.update_if(|s, tx| s.script.poll(now, tx));
if rt.frame(DT) || stale {
asked += 1;
}
}
(frames, asked, rt.state.script.metrics().vm_calls - before)
}
fn memo_hit(n: usize) -> (Stat, u64) {
let (mut rt, _) = runtime();
let mut calls = 0;
let mut samples = Vec::with_capacity(n);
for _ in 0..n {
rt.update(|s, _| s.host_ticks += 1);
rt.frame(DT);
samples.push(us(rt.state.view_time.get()));
calls += rt.state.view_calls.get();
}
(Stat::of(samples), calls)
}
/// Wall time, and (on Windows) the time the thread actually ran, which leaves out the time
/// other processes on a busy machine held its core.
fn rebuild20(n: usize) -> (Stat, Option<Stat>) {
let script = Script::new("panel20", sources());
for _ in 0..50 {
drop(script.render_uncached::<State>("panel20", true));
}
let per_us = cpu::cycles_per_us();
let (mut wall, mut ran) = (Vec::with_capacity(n), Vec::with_capacity(n));
for _ in 0..n {
let (start, cycles) = (now(), cpu::cycles());
let el = script.render_uncached::<State>("panel20", true);
wall.push(us(start.elapsed()));
if let (Some(per_us), Some(a), Some(b)) = (per_us, cycles, cpu::cycles()) {
ran.push((b - a) as f64 / per_us);
}
drop(el);
}
(Stat::of(wall), (!ran.is_empty()).then(|| Stat::of(ran)))
}
/// The thread's cycle count (`QueryThreadCycleTime`), and its rate, measured against the clock.
mod cpu {
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn cycles() -> Option<u64> {
unsafe extern "system" {
fn GetCurrentThread() -> isize;
fn QueryThreadCycleTime(thread: isize, cycles: *mut u64) -> i32;
}
let mut c = 0;
// SAFETY: the pseudo-handle for this thread, and a valid out pointer.
(unsafe { QueryThreadCycleTime(GetCurrentThread(), &mut c) } != 0).then_some(c)
}
#[cfg(not(windows))]
pub fn cycles() -> Option<u64> {
None
}
/// The fastest of a few 20 ms spins: a spin the scheduler interrupted reads slow.
pub fn cycles_per_us() -> Option<f64> {
(0..5)
.filter_map(|_| {
let (start, c0) = (rune::time::now(), cycles()?);
while start.elapsed().as_millis() < 20 {
std::hint::spin_loop();
}
Some((cycles()? - c0) as f64 / (start.elapsed().as_secs_f64() * 1e6))
})
.reduce(f64::max)
}
}
fn scroll() -> (Stat, Stat, u64) {
let (mut rt, _) = runtime();
let rows_before = rt.state.script.metrics().rows;
let (mut script, mut frame) = (Vec::new(), Vec::new());
// 40 points a frame at 120 fps (4,800 pt/s): one or two new rows enter most frames.
for _ in 0..360 {
let m = rt.state.script.metrics();
let start = now();
rt.wheel(360.0, 400.0, -40.0);
rt.frame(DT);
frame.push(us(start.elapsed()));
script.push(us(rt.state.script.metrics().vm_time - m.vm_time));
}
(Stat::of(script), Stat::of(frame), rt.state.script.metrics().rows - rows_before)
}
fn reload(n: usize) -> (Stat, Stat, Stat, bool) {
let script = Script::new("panel", sources());
script.call("select", [Data::Number(7.0)]).ok();
let base = sources();
let init = base.get("init.luau").unwrap_or_default().to_owned();
let (mut total, mut compile, mut swap) = (Vec::new(), Vec::new(), Vec::new());
let mut kept = true;
for i in 0..n {
let edited: Sources = base.clone().with("init.luau", format!("{init}\n-- edit {i}\n"));
match script.reload(edited) {
Ok(r) => {
total.push(us(r.compile + r.swap));
compile.push(us(r.compile));
swap.push(us(r.swap));
}
Err(e) => {
kept = false;
eprintln!("reload failed: {e}");
}
}
kept &= script.query("selected", []).ok().and_then(|d| d.as_f64()) == Some(7.0);
}
(Stat::of(total), Stat::of(compile), Stat::of(swap), kept)
}
impl Report {
pub fn json(&self) -> String {
format!(
concat!(
r#"{{"native_code":{},"idle":{{"frames":{},"frames_asked":{},"vm_calls":{}}},"#,
r#""memo_hit":{{"view":{},"vm_calls":{}}},"rebuild20":{},"rebuild20_thread_time":{},"#,
r#""scroll":{{"script_per_frame":{},"frame":{},"rows_built":{}}},"#,
r#""reload":{{"total":{},"compile":{},"swap":{},"state_kept":{}}},"checks":[{}]}}"#
),
self.native_code,
self.idle.0,
self.idle.1,
self.idle.2,
self.memo_hit.0.json(),
self.memo_hit.1,
self.rebuild20.0.json(),
self.rebuild20.1.map_or("null".to_owned(), |s| s.json()),
self.scroll.0.json(),
self.scroll.1.json(),
self.scroll.2,
self.reload.0.json(),
self.reload.1.json(),
self.reload.2.json(),
self.reload.3,
self.checks
.iter()
.map(|c| format!(r#"{{"name":{:?},"ok":{},"detail":{:?}}}"#, c.name, c.ok, c.detail))
.collect::<Vec<_>>()
.join(","),
)
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let row = |name: &str, s: &Stat, gate: &str| format!("{name:<34} n={:<5} mean {:>9.2} µs p50 {:>9.2} p99 {:>9.2} max {:>9.2} gate {gate}", s.n, s.mean, s.p50, s.p99, s.max);
writeln!(f, "Luau {}", if self.native_code { "native code (luau-jit)" } else { "interpreter" })?;
writeln!(f, "idle: {} frames polled, {} asked for a frame, {} VM calls (gate: 0)", self.idle.0, self.idle.1, self.idle.2)?;
writeln!(f, "{} VM calls {}", row("memo hit (Script::view)", &self.memo_hit.0, "≤ 5 µs"), self.memo_hit.1)?;
writeln!(f, "{}", row("20-row panel rebuild", &self.rebuild20.0, "≤ 120 µs"))?;
if let Some(s) = &self.rebuild20.1 {
writeln!(f, "{}", row("20-row panel rebuild, thread time", s, "≤ 120 µs"))?;
}
writeln!(f, "{}", row("scroll frame, script time", &self.scroll.0, "≤ 300 µs"))?;
writeln!(f, "{} rows built {}", row("scroll frame, whole frame", &self.scroll.1, "—"), self.scroll.2)?;
writeln!(f, "{}", row("hot reload, compile + swap", &self.reload.0, "≤ 5,000 µs"))?;
writeln!(f, "{}", row("hot reload, compile", &self.reload.1, "—"))?;
writeln!(f, "{} state kept {}", row("hot reload, swap", &self.reload.2, "—"), self.reload.3)?;
for c in &self.checks {
writeln!(f, "check {:<24} {} {}", c.name, if c.ok { "ok " } else { "FAIL" }, c.detail)?;
}
Ok(())
}
}
+10
View File
@@ -0,0 +1,10 @@
//! `cargo run -p luau-panel --bin luau-bench --profile perf`: the Luau performance gates,
//! measured headless on the example panel. Prints a table, then the numbers as JSON.
#![forbid(unsafe_code)]
fn main() {
let report = luau_panel::bench::run(luau_panel::bench::Scale::Native);
println!("{report}");
println!("{}", report.json());
}
+129
View File
@@ -0,0 +1,129 @@
//! Behaviour the panel doesn't exercise, shown on small scripts: the watchdog, a failing render,
//! `require` by Luau's rules, a cycle, numbers crossing to Rust, and a host signal and async
//! call. Printed by `luau-bench` and `luau_bench()` next to the performance numbers.
use std::time::Duration;
use rune::time::now;
use rune_luau::mlua::Value;
use rune_luau::{Data, ErrorKind, Script, ScriptOptions, Sources};
use crate::State;
pub struct Check {
pub name: &'static str,
pub ok: bool,
pub detail: String,
}
pub fn run() -> Vec<Check> {
vec![watchdog(), render_error(), require_rules(), require_cycle(), numbers(), host_signal_and_async()]
}
fn check(name: &'static str, ok: bool, detail: impl Into<String>) -> Check {
Check { name, ok, detail: detail.into() }
}
/// `while true do end` stops at the 250 ms limit with a timeout, and the script keeps working.
fn watchdog() -> Check {
let script = Script::new("spin", Sources::single("return { spin = function() while true do end end, ok = function() return 1 end }"));
let start = now();
let err = script.query("spin", []).err();
let took = start.elapsed();
let still = script.query("ok", []).ok().and_then(|d| d.as_i64());
let ok = err.as_ref().is_some_and(|e| e.kind == ErrorKind::Timeout) && took < Duration::from_millis(260) && still == Some(1);
check("watchdog", ok, format!("stopped after {:.1} ms ({:?}); the next call returned {still:?}", took.as_secs_f64() * 1e3, err.map(|e| e.kind)))
}
/// A render that raises shows the error card instead of panicking, and the log has the error.
fn render_error() -> Check {
let script = Script::new("broken", Sources::single("local ui = require('@rune/ui')\nreturn function() local t = nil; return ui.text(t.field) end"));
let el = script.render_uncached::<State>("render", true);
drop(el);
let logged = script.log().iter().any(|l| l.message.contains("attempt to index nil"));
check("render error", logged, script.log().last().map(|l| l.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default())
}
/// Luau's rules: from `init.luau` (which stands for its folder), `@self/x` is `x.luau` in the
/// folder and `./x` would be beside the folder, so it fails; from `views/row.luau`, `./util`
/// is `views/util.luau`, and the folder's `.luaurc` alias `@lib` resolves.
fn require_rules() -> Check {
let sources = Sources::new()
.with("init.luau", "local row = require('@self/views/row')\nlocal escaped = pcall(require, './views/row')\nreturn { probe = function() return row .. '|' .. tostring(escaped) end }")
.with("views/row.luau", "return 'row+' .. require('./util') .. '+' .. require('@lib/util')")
.with("views/util.luau", "return 'util'")
.with(".luaurc", r#"{ "aliases": { "lib": "./views" } }"#);
let script = Script::new("req", sources);
let got = script.query("probe", []).map(|d| d.as_str().unwrap_or_default().to_owned()).unwrap_or_else(|e| e.message);
check("require", got == "row+util+util|false", got)
}
fn require_cycle() -> Check {
let sources = Sources::new().with("init.luau", "return require('@self/a')").with("a.luau", "return require('./b')").with("b.luau", "return require('./a')");
let script = Script::new("cycle", sources);
let err = script.error().map(|e| e.message).unwrap_or_default();
check("require cycle", err.contains("require cycle: init.luau -> a.luau -> b.luau -> a.luau"), err.lines().next().unwrap_or_default().to_owned())
}
/// Whole numbers come across as integers, through `Data` and through mlua's serde.
fn numbers() -> Check {
let script = Script::new("nums", Sources::single("return { values = function() return { small = 3, big = 2^40, half = 2.5 } end }"));
let data = script.query("values", []).unwrap_or_default();
let via_data = (data.get("small").as_i64(), data.get("big").as_i64(), data.get("half").as_f64());
let serde = script.with_lua(|lua| {
use rune_luau::mlua::LuaSerdeExt;
let t: Value = lua.load("return { small = 3, big = 2^40 }").eval().unwrap_or(Value::Nil);
let small = lua.from_value::<std::collections::HashMap<String, i64>>(t.clone()).map_err(|e| e.to_string());
small.map(|m| (m.get("small").copied(), m.get("big").copied()))
});
#[derive(serde::Deserialize, Debug, PartialEq)]
struct Values {
small: i64,
big: i64,
half: f64,
}
let decoded = data.decode::<Values>().map_err(|e| e.to_string());
let ok = via_data == (Some(3), Some(1 << 40), Some(2.5)) && decoded == Ok(Values { small: 3, big: 1 << 40, half: 2.5 });
check("numbers", ok, format!("Data: {via_data:?}; Data::decode: {decoded:?}; mlua serde into i64: {serde:?}"))
}
/// A host signal fires into a connection, and a host async call resumes its task.
fn host_signal_and_async() -> Check {
let options = ScriptOptions::new().setup(|host| {
let signal = host.signal("changed")?;
let double = host.async_function("double", |_, args, done| {
let n = match args.front() {
Some(Value::Integer(i)) => *i as f64,
Some(Value::Number(n)) => *n,
_ => 0.0,
};
rune_luau::spawn_blocking(move || done.complete(n * 2.0));
Ok(())
})?;
let module = host.lua().create_table()?;
module.raw_set("changed", signal)?;
module.raw_set("double", double)?;
host.register_module("@app/host", module)
});
let src = "local host = require('@app/host')\nlocal seen = {}\nhost.changed:Connect(function(v) seen.signal = v end)\nreturn { start = function() seen.async = host.double(21) end, seen = function() return seen end }";
let script = Script::with_options("host", Sources::single(src), options);
script.fire("changed", [Data::from("hello")]);
script.call("start", []).ok();
// The async result arrives on a worker thread; poll until the task resumes.
let mut rt = rune::Runtime::new((), |_: &(), _: &mut rune::Cx<()>| rune::el(), (10.0, 10.0), rune::Env::new(true, 1.0));
let mut now = 0.0;
for _ in 0..200 {
now += 1.0 / 120.0;
rt.update_if(|_, tx| script.poll(now, tx));
if script.query("seen", []).ok().is_some_and(|d| d.get("async") != &Data::Nil) {
break;
}
// On the web the result arrives in a microtask, after this synchronous loop.
#[cfg(not(target_arch = "wasm32"))]
std::thread::sleep(Duration::from_millis(1));
}
let seen = script.query("seen", []).unwrap_or_default();
let async_done = seen.get("async").as_i64() == Some(42) || cfg!(target_arch = "wasm32");
let ok = seen.get("signal").as_str() == Some("hello") && async_done;
check("host signal and async", ok, format!("{seen:?} {:?}", script.log().iter().map(|l| l.message.clone()).collect::<Vec<_>>()))
}
+88
View File
@@ -0,0 +1,88 @@
//! A Rune app hosting a Luau script (`scripts/panel`): a header with buttons, a pulse driven
//! by `task.wait`, a signal, and a 1,000-row `ui.virtualList`. Native builds watch the script
//! folder, so saving a `.luau` file reloads the panel in place. The same script runs on the web:
//! `scripts/web-build.sh luau-panel` (with `WASI_SDK_PATH` set).
//!
//! `cargo run -p luau-panel`; `cargo run -p luau-panel --bin luau-bench --profile perf` measures
//! the performance gates (idle, memo hit, 20-row rebuild, list scroll, hot reload).
use std::cell::Cell;
use std::time::Duration;
use rune::time::now;
use rune::{AppSpec, Cx, El, Tx, Waker, col};
use rune_luau::{Script, Sources};
pub mod bench;
pub mod checks;
pub struct State {
pub script: Script,
/// Host state the script doesn't read: bumping it re-runs the view, not the script.
pub host_ticks: u64,
/// How long the last `Script::view` call took, and the VM entries it made.
pub view_time: Cell<Duration>,
pub view_calls: Cell<u64>,
}
impl State {
pub fn new(script: Script) -> Self {
State { script, host_ticks: 0, view_time: Cell::new(Duration::ZERO), view_calls: Cell::new(0) }
}
}
/// The panel's files, built into the binary.
pub fn sources() -> Sources {
Sources::new()
.with("init.luau", include_str!("../scripts/panel/init.luau"))
.with("rows.luau", include_str!("../scripts/panel/rows.luau"))
}
fn init() -> State {
#[cfg(not(target_arch = "wasm32"))]
{
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/scripts/panel");
if let Ok(sources) = Sources::from_dir(dir) {
let options = rune_luau::ScriptOptions::new().on_log(|level, line| eprintln!("luau-panel {level:?}: {line}"));
let script = Script::with_options("panel", sources, options);
if let Err(e) = script.watch(dir) {
eprintln!("luau-panel: not watching {dir}: {e}");
}
return State::new(script);
}
}
State::new(Script::new("panel", sources()))
}
pub fn view(s: &State, cx: &mut Cx<State>) -> El {
let calls = s.script.metrics().vm_calls;
let start = now();
let panel = s.script.view(cx);
s.view_time.set(start.elapsed());
s.view_calls.set(s.script.metrics().vm_calls - calls);
col().w_full().h_full().child(panel)
}
fn setup(s: &mut State, waker: Waker) {
s.script.set_waker(waker);
}
fn poll(s: &mut State, now: f64, tx: &mut Tx) -> bool {
s.script.poll(now, tx)
}
pub fn spec() -> AppSpec<State> {
AppSpec { setup: Some(setup), poll: Some(poll), ..AppSpec::new("Luau panel", (720.0, 640.0), init, view) }
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(start))]
pub fn start() {
rune::run(spec());
}
/// Runs the performance measurements in the page and returns them as JSON.
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn luau_bench() -> String {
bench::run(bench::Scale::Web).json()
}
+5
View File
@@ -0,0 +1,5 @@
#![forbid(unsafe_code)]
fn main() {
luau_panel::start();
}
+89
View File
@@ -0,0 +1,89 @@
// Browser proof for luau-panel: the Luau panel renders in Rune's web build, rests at zero frames,
// scrolls its 1,000-row list, answers presses, and reports the interpreter's performance numbers.
// Requires Playwright. Usage: node web-proof.mjs [web dir] [output dir]
// (build first: scripts/web-build.sh luau-panel --out target/web-luau, with WASI_SDK_PATH set).
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { resolve, extname, sep } from 'node:path';
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
const root = resolve(process.argv[2] || 'target/web-luau');
const output = resolve(process.argv[3] || 'target/web-luau-proof');
await mkdir(output, { recursive: true });
const server = createServer(async (request, response) => {
if (request.url === '/favicon.ico') { response.writeHead(204).end(); return; }
const path = resolve(root, '.' + new URL(request.url, 'http://localhost').pathname.replace(/\/$/, '/index.html'));
if (!path.startsWith(root + sep)) { response.writeHead(403).end(); return; }
try {
const bytes = await readFile(path);
response.setHeader('Content-Type', ({ '.wasm': 'application/wasm', '.js': 'text/javascript', '.html': 'text/html' })[extname(path)] || 'application/octet-stream');
response.end(bytes);
} catch { response.writeHead(404).end(); }
});
await new Promise(done => server.listen(0, '127.0.0.1', done));
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH, args: ['--enable-unsafe-webgpu'] });
const errors = [];
const log = [];
try {
const context = await browser.newContext({ viewport: { width: 720, height: 640 }, deviceScaleFactor: 1, colorScheme: 'dark',
recordVideo: { dir: output, size: { width: 720, height: 640 } } });
const page = await context.newPage();
page.on('pageerror', error => errors.push(error.message));
page.on('console', message => { log.push(`${message.type()}: ${message.text()}`); if (message.type() === 'error') errors.push(message.text()); });
await page.addInitScript(() => {
Error.stackTraceLimit = 100;
window.__proof = { submits: 0, rafs: 0 };
const raf = window.requestAnimationFrame;
window.requestAnimationFrame = callback => { window.__proof.rafs++; return raf.call(window, callback); };
if (!globalThis.GPUQueue) return;
const submit = GPUQueue.prototype.submit;
GPUQueue.prototype.submit = function (...args) { window.__proof.submits++; return submit.apply(this, args); };
});
await page.goto(`http://127.0.0.1:${server.address().port}`);
await page.waitForFunction(() => window.__proof?.submits > 0, null, { timeout: 60000 }).catch(async error => {
console.log(log.join('\n'), errors.join('\n'), await page.locator('body').innerText());
throw error;
});
await page.waitForTimeout(1500);
const counts = () => page.evaluate(() => ({ ...window.__proof }));
const idle = async ms => { const a = await counts(); await page.waitForTimeout(ms); const b = await counts(); return { submits: b.submits - a.submits, rafs: b.rafs - a.rafs, ms }; };
const result = { idle: await idle(3000) };
await page.screenshot({ path: `${output}/01-loaded.png` });
// Scroll the 1,000-row list: 120 wheel steps of 40 px, one per frame.
const before = await counts();
await page.mouse.move(360, 400);
for (let i = 0; i < 120; i++) { await page.mouse.wheel(0, 40); await page.waitForTimeout(8); }
await page.waitForTimeout(500);
result.scroll = { submits: (await counts()).submits - before.submits };
await page.screenshot({ path: `${output}/02-scrolled.png` });
result.idleAfterScroll = await idle(2000);
// Press a row, then Pulse (a task.wait countdown), then Ping (a signal).
await page.mouse.click(300, 300);
await page.waitForTimeout(300);
await page.screenshot({ path: `${output}/03-selected.png` });
await page.mouse.click(110, 52);
await page.waitForTimeout(300);
await page.screenshot({ path: `${output}/04-pulsing.png` });
await page.waitForTimeout(1500);
await page.mouse.click(160, 52);
await page.waitForTimeout(300);
await page.screenshot({ path: `${output}/05-pinged.png` });
result.idleAfterTasks = await idle(2000);
// The interpreter's numbers, measured in this page by the same code as the native bench.
result.bench = JSON.parse(await page.evaluate(async () => (await import('./app.js')).luau_bench()));
result.errors = errors;
await writeFile(`${output}/web-proof.json`, JSON.stringify(result, null, 2));
await writeFile(`${output}/console.txt`, log.join('\n'));
console.log(JSON.stringify(result, null, 2));
assert.equal(result.idle.submits, 0, 'an idle page draws nothing');
assert.ok(result.scroll.submits > 30, 'scrolling draws');
assert.equal(result.idleAfterTasks.submits, 0, 'the page rests after its tasks finish');
assert.deepEqual(errors, []);
await context.close();
} finally {
await browser.close();
server.close();
}