1use std::cell::{OnceCell, RefCell};
4use std::collections::VecDeque;
5use std::ffi::c_void;
6use std::sync::OnceLock;
7
8use redjs::api::{Context, Error, Value};
9use redjs::ffi::{self, RjsPumpStats};
10use redjs::webapi::fsutil::{ContentReadFn, ContentSinkFn};
11
12pub use redjs::web::{PUMP_MICROTASKS, PUMP_RAF, PUMP_TIMERS};
13
14#[derive(Debug, Clone)]
15pub struct JsError {
16 pub header: String,
17 pub stack: String,
18}
19
20const NO_DISK_ROOT: &str = r"\\?\skathi-no-disk-root";
22
23pub const SK_USER_AGENT: &str = redjs::webapi::navigator::DEFAULT_USER_AGENT;
24
25fn apply_user_agent() {
26 redjs::webapi::navigator::set_user_agent(Some(SK_USER_AGENT));
27}
28
29pub const SK_PUMP_DELIVERY_BUDGET_US: u32 = 4000;
31
32pub const SK_PUMP_DELIVERY_MIN_US: u32 = 500;
33
34pub fn delivery_budget_us(frame_ms: Option<f32>) -> u32 {
35 match frame_ms {
36 Some(ms) if ms.is_finite() && ms > 0.0 => {
37 ((ms * 250.0) as u32).clamp(SK_PUMP_DELIVERY_MIN_US, SK_PUMP_DELIVERY_BUDGET_US)
38 }
39 _ => SK_PUMP_DELIVERY_BUDGET_US,
40 }
41}
42
43fn apply_pump_budget() {
44 redjs::web::set_pump_budget_us(SK_PUMP_DELIVERY_BUDGET_US);
45}
46
47fn share_clock_with_effects() {
50 let now = std::time::Instant::now();
51 let elapsed = std::time::Duration::from_secs_f64(redjs::web::now_ms().max(0.0) / 1000.0);
52 gpui::set_effect_clock_origin(now.checked_sub(elapsed).unwrap_or(now));
53}
54
55pub const SK_JSC_OPTIONS: &str = "jitPolicyScale=0.5";
58
59fn jsc_options() -> std::ffi::CString {
60 let kept: Vec<&str> = SK_JSC_OPTIONS
61 .split(',')
62 .filter(|opt| {
63 let name = opt.split('=').next().unwrap_or(opt);
64 std::env::var_os(format!("JSC_{name}")).is_none()
65 })
66 .collect();
67 std::ffi::CString::new(kept.join(",")).expect("SK_JSC_OPTIONS holds no NUL")
68}
69
70pub fn set_frame_budget_ms(frame_ms: Option<f32>) {
71 let us = delivery_budget_us(frame_ms);
72 if redjs::web::pump_budget_us() != us {
73 redjs::web::set_pump_budget_us(us);
74 }
75}
76
77thread_local! {
78 static RUNTIME: OnceCell<JsRuntime> = const { OnceCell::new() };
79 static ERRORS: RefCell<VecDeque<JsError>> = const { RefCell::new(VecDeque::new()) };
80}
81
82pub struct JsRuntime {
84 ctx: Context,
85}
86
87impl JsRuntime {
88 pub fn init() {
91 static BOOTED: OnceLock<std::thread::ThreadId> = OnceLock::new();
92 let here = std::thread::current().id();
93 if BOOTED.set(here).is_err() {
94 panic!(
95 "JsRuntime::init called a second time in this process (first on {:?}, now on {:?}). \
96 The runtime boots once per process, and a second boot aborts it. A test that needs \
97 JS runs its body through sk_runtime::testing::on_js_thread instead.",
98 BOOTED.get().expect("set"),
99 here
100 );
101 }
102 crate::bridge::install_panic_hook();
103 unsafe {
104 let options = jsc_options();
106 let rc = ffi::redjs_init(options.as_ptr());
107 assert_eq!(rc, 0, "redjs_init failed: {rc}");
108 }
109 apply_user_agent();
110 apply_pump_budget();
111 #[cfg(feature = "webgpu")]
112 redjs_webgpu::register();
113 let ctx = Context::new();
114 unsafe {
115 let rc = ffi::redjs_web_install(ctx.raw());
116 assert_eq!(rc, 0, "redjs_web_install failed: {rc}");
117 share_clock_with_effects();
118 let root: Vec<u16> = NO_DISK_ROOT.encode_utf16().collect();
121 let rc = ffi::redjs_webshim_install(
122 ctx.raw(),
123 root.as_ptr(),
124 root.len(),
125 root.as_ptr(),
126 root.len(),
127 );
128 assert_eq!(rc, 0, "redjs_webshim_install failed: {rc}");
129 ffi::redjs_set_uncaught_handler(on_uncaught as *const c_void);
130 crate::unsupported::install(ctx.raw());
131 crate::host::install(ctx.raw());
132 crate::history::install(ctx.raw());
133 }
134 RUNTIME.with(|r| {
135 r.set(JsRuntime { ctx })
136 .unwrap_or_else(|_| unreachable!("BOOTED admits one init"))
137 });
138 }
139
140 pub fn with<R>(f: impl FnOnce(&JsRuntime) -> R) -> R {
141 RUNTIME.with(|r| f(r.get().expect("JsRuntime::init has not run on this thread")))
142 }
143
144 pub fn try_with<R>(f: impl FnOnce(&JsRuntime) -> R) -> Option<R> {
145 RUNTIME.with(|r| r.get().map(f))
146 }
147
148 pub fn raw(&self) -> *mut c_void {
149 self.ctx.raw()
150 }
151
152 pub fn ctx(&self) -> &Context {
153 &self.ctx
154 }
155
156 pub fn eval(&self, src: &str, url: &str) -> Result<(), JsError> {
157 match self.ctx.eval_named(src, url) {
158 Ok(_) => Ok(()),
159 Err(Error::Exception(e)) => Err(self.describe(e)),
160 Err(e) => Err(JsError {
161 header: format!("engine error: {e}"),
162 stack: String::new(),
163 }),
164 }
165 }
166
167 pub fn register(&self, name: &str, arity: u32, f: *const c_void) {
168 let v = unsafe { self.ctx.function_sysv(name, arity, f) }
169 .unwrap_or_else(|e| panic!("registering host fn {name}: {e:?}"));
170 self.ctx
171 .global_set(name, v)
172 .unwrap_or_else(|e| panic!("defining global {name}: {e:?}"));
173 }
174
175 pub fn pump(&self, flags: u32) -> RjsPumpStats {
176 let mut stats = RjsPumpStats {
177 now: 0.0,
178 timers_fired: 0,
179 raf_fired: 0,
180 raf_pending: 0,
181 timers_active: 0,
182 next_timer_deadline: -1.0,
183 };
184 unsafe {
185 ffi::redjs_lock(self.ctx.raw());
186 ffi::redjs_pump(self.ctx.raw(), flags, &mut stats);
187 ffi::redjs_unlock(self.ctx.raw());
188 }
189 stats
190 }
191
192 pub fn drain_errors(&self) -> Vec<JsError> {
193 ERRORS.with(|e| e.borrow_mut().drain(..).collect())
194 }
195
196 pub fn set_content_provider(
200 &self,
201 f: impl Fn(&str) -> Option<Vec<u8>> + Send + Sync + 'static,
202 ) {
203 if PROVIDER.set(Box::new(f)).is_err() {
204 eprintln!(
205 "[sk-runtime] set_content_provider called twice — keeping the first provider"
206 );
207 return;
208 }
209 unsafe { ffi::redjs_content_provider_set(self.ctx.raw(), content_read as *const c_void) };
210 }
211
212 pub fn clear_content_provider(&self) {
213 unsafe { ffi::redjs_content_provider_set(self.ctx.raw(), std::ptr::null()) };
214 }
215
216 pub fn describe(&self, exc: Value) -> JsError {
217 let (msg, stack) = self.ctx.error_info(exc);
218 let name = self
219 .ctx
220 .get(exc, &self.ctx.atom("name"))
221 .ok()
222 .and_then(|v| self.ctx.read_string(v).ok())
223 .unwrap_or_default();
224 let header = match (name.is_empty(), msg.is_empty()) {
225 (false, false) => format!("{name}: {msg}"),
226 (false, true) => name,
227 (true, false) => msg,
228 (true, true) => self.ctx.to_rust_string(exc).unwrap_or_default(),
229 };
230 JsError { header, stack }
231 }
232}
233
234type Provider = Box<dyn Fn(&str) -> Option<Vec<u8>> + Send + Sync>;
235static PROVIDER: OnceLock<Provider> = OnceLock::new();
236
237const _: ContentReadFn = content_read;
238
239unsafe extern "C" fn content_read(
241 path_ptr: *const u8,
242 path_len: usize,
243 sink: ContentSinkFn,
244 sink_ctx: *mut c_void,
245) -> i32 {
246 const MISS: i32 = 1;
247 let Some(provider) = PROVIDER.get() else {
248 return MISS;
249 };
250 if path_ptr.is_null() {
251 return MISS;
252 }
253 let bytes = core::slice::from_raw_parts(path_ptr, path_len);
254 let Ok(key) = std::str::from_utf8(bytes) else {
255 return MISS;
256 };
257 let found = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| provider(key)));
258 match found {
259 Ok(Some(data)) => {
260 sink(sink_ctx, data.as_ptr(), data.len());
261 0
262 }
263 Ok(None) => MISS,
264 Err(_) => {
265 eprintln!("[sk-runtime] content provider panicked for {key:?} — treated as a miss");
266 MISS
267 }
268 }
269}
270
271unsafe extern "C" fn on_uncaught(g: *mut c_void, exc: u64) {
274 let _ = std::panic::catch_unwind(|| {
275 let err = describe_raw(g, exc);
276 ERRORS.with(|e| e.borrow_mut().push_back(err));
277 });
278}
279
280fn describe_raw(g: *mut c_void, exc: u64) -> JsError {
281 unsafe {
282 let (mut msg_v, mut stack_v) = (0u64, 0u64);
283 ffi::redjs_error_info(g, exc, &mut msg_v, &mut stack_v);
284 let msg = redjs::webapi::util::read_string(g, msg_v).unwrap_or_default();
285 let stack = redjs::webapi::util::read_string(g, stack_v).unwrap_or_default();
286 let name_v = redjs::webapi::util::get(g, exc, "name");
287 let name = redjs::webapi::util::read_string(g, name_v).unwrap_or_default();
288 let header = if name.is_empty() {
289 msg
290 } else {
291 format!("{name}: {msg}")
292 };
293 JsError { header, stack }
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300
301 #[test]
302 fn navigator_reports_the_skathi_user_agent() {
303 assert_eq!(SK_USER_AGENT, redjs::webapi::navigator::DEFAULT_USER_AGENT);
304 unsafe { assert_eq!(ffi::redjs_init(std::ptr::null()), 0) };
305 apply_user_agent();
306 let ctx = Context::new();
307 unsafe {
308 assert_eq!(ffi::redjs_web_install(ctx.raw()), 0);
309 let root: Vec<u16> = NO_DISK_ROOT.encode_utf16().collect();
310 assert_eq!(
311 ffi::redjs_webshim_install(
312 ctx.raw(),
313 root.as_ptr(),
314 root.len(),
315 root.as_ptr(),
316 root.len()
317 ),
318 0
319 );
320 }
321 let read = |src: &str| ctx.to_rust_string(ctx.eval(src).unwrap()).unwrap();
322 assert_eq!(read("navigator.userAgent"), SK_USER_AGENT);
323 assert_eq!(
324 read("navigator.appVersion"),
325 redjs::webapi::navigator::app_version(SK_USER_AGENT)
326 );
327 assert_eq!(
328 read("navigator.platform"),
329 redjs::webapi::navigator::platform(SK_USER_AGENT)
330 );
331 #[cfg(target_os = "macos")]
332 assert_eq!(read("navigator.platform"), "MacIntel");
333 #[cfg(target_os = "windows")]
334 assert_eq!(read("navigator.platform"), "Win32");
335 assert_eq!(read("String(navigator instanceof Navigator)"), "true");
336 }
337
338 #[cfg(feature = "indexeddb")]
339 #[test]
340 fn indexeddb_answers_an_awaited_chain_within_a_few_frames() {
341 unsafe { assert_eq!(ffi::redjs_init(std::ptr::null()), 0) };
342 apply_pump_budget();
343 assert_eq!(redjs::web::pump_budget_us(), SK_PUMP_DELIVERY_BUDGET_US);
344 let ctx = Context::new();
345 unsafe {
346 assert_eq!(ffi::redjs_web_install(ctx.raw()), 0);
347 let root: Vec<u16> = NO_DISK_ROOT.encode_utf16().collect();
348 assert_eq!(
349 ffi::redjs_webshim_install(
350 ctx.raw(),
351 root.as_ptr(),
352 root.len(),
353 root.as_ptr(),
354 root.len()
355 ),
356 0
357 );
358 }
359 let read = |src: &str| ctx.to_rust_string(ctx.eval(src).unwrap()).unwrap();
360 assert_eq!(read("typeof indexedDB + ',' + typeof IDBKeyRange + ',' + typeof navigator.storage.estimate"), "object,function,function");
361 read(
362 "globalThis.__r = '';
363 const p = (q) => new Promise((res, rej) => { q.onsuccess = () => res(q.result); q.onerror = () => rej(q.error); });
364 (async () => {
365 const open = indexedDB.open('sk-runtime-chain', 1);
366 open.onupgradeneeded = () => open.result.createObjectStore('s');
367 const db = await p(open);
368 const tx = db.transaction('s', 'readwrite');
369 for (let i = 0; i < 200; i++) tx.objectStore('s').put(i * 2, i);
370 await new Promise((res) => { tx.oncomplete = res; });
371 let sum = 0;
372 for (let i = 0; i < 200; i++) sum += await p(db.transaction('s').objectStore('s').get(i));
373 return sum;
374 })().then((v) => { globalThis.__r = String(v); }, (e) => { globalThis.__r = 'ERR ' + e; });
375 ''",
376 );
377 let mut frames = 0;
378 let out = loop {
379 unsafe {
380 ffi::redjs_lock(ctx.raw());
381 ffi::redjs_pump(
382 ctx.raw(),
383 PUMP_TIMERS | PUMP_RAF | PUMP_MICROTASKS,
384 std::ptr::null_mut(),
385 );
386 ffi::redjs_unlock(ctx.raw());
387 }
388 frames += 1;
389 let r = read("globalThis.__r");
390 if !r.is_empty() || frames > 500 {
391 break r;
392 }
393 std::thread::sleep(std::time::Duration::from_millis(2));
394 };
395 assert_eq!(out, "39800");
396 assert!(frames <= 10, "200 awaited gets took {frames} frames");
397 }
398}