localharness 0.76.0

Agents that own themselves: one Rust crate that's both an agent SDK (streaming, tools, hooks, policies, triggers, MCP) and a wallet-owning, self-sovereign agent that runs in the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Browser OPFS-backed implementation of [`Filesystem`].
//!
//! Uses the Origin Private File System exposed via
//! `navigator.storage.getDirectory()`. Each browser tab/origin gets its
//! own private root directory.
//!
//! ## Atomicity
//!
//! `write_atomic` relies on OPFS's `FileSystemWritableFileStream`
//! semantics: writes are buffered to a swap file and the original is
//! atomically replaced on `close()`. A page reload mid-write leaves
//! the original file intact.
//!
//! ## Path handling
//!
//! OPFS has no native path syntax — only handles. This impl splits
//! incoming paths on `/`, drops empty components, and resolves each
//! component as a directory (or final file). Leading slashes are
//! ignored; OPFS-rooted paths and relative paths are equivalent.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use async_trait::async_trait;
use js_sys::{Function, Object, Promise, Reflect, Uint8Array};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{
    File, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions,
    FileSystemGetFileOptions, FileSystemHandle, FileSystemHandleKind, FileSystemRemoveOptions,
    FileSystemWritableFileStream, MessageEvent, Worker,
};

use super::{DirEntry, EntryKind, Filesystem, Metadata, WalkEntry};
use crate::error::{Error, Result};

/// Wall-clock bound on a single OPFS write (either path). The 2026-06-18 iOS
/// gate existed because a WebKit write stalled FOREVER and froze the
/// single-thread wasm app mid-onboarding — a pathological engine must surface
/// as an ERROR the UI can show, never an infinite hang.
const WRITE_TIMEOUT_MS: u32 = 15_000;

/// Hard cap on entries a single `walk` collects. find_file/search_directory
/// cap their own RESULTS, but they collect the whole walk first, so without
/// this a walk over a huge tree would exhaust memory. Mirrors
/// `NativeFilesystem::MAX_WALK_ENTRIES`; 200k is far beyond any real workspace.
const MAX_WALK_ENTRIES: usize = 200_000;

/// Filesystem backed by the browser's Origin Private File System.
///
/// Cheap to clone: holds an `Rc` to the OPFS root handle once acquired.
#[derive(Debug, Clone, Default)]
pub struct OpfsFilesystem {
    // Cache the OPFS root after first acquisition; getDirectory()
    // returns the same logical handle every time but each call is async.
    root: Rc<RefCell<Option<FileSystemDirectoryHandle>>>,
}

impl OpfsFilesystem {
    pub fn new() -> Self {
        Self::default()
    }

    async fn root_handle(&self) -> Result<FileSystemDirectoryHandle> {
        // NEVER hold a `Ref`/`RefMut` across the `getDirectory().await` below.
        // The single-threaded wasm executor interleaves tasks at await points,
        // and on iOS WebKit's microtask timing a borrow held across an await can
        // be re-entered by a concurrent OPFS op → "RefCell already borrowed".
        // Take an OWNED clone out of the borrow in its own statement, so the
        // guard is dropped before we await.
        let cached = self.root.borrow().clone();
        if let Some(h) = cached {
            return Ok(h);
        }
        let window = web_sys::window()
            .ok_or_else(|| Error::fs("getDirectory", "", "no window: not in a browser"))?;
        let storage = window.navigator().storage();
        let promise = storage.get_directory();
        let val = JsFuture::from(promise)
            .await
            .map_err(|e| Error::fs("getDirectory", "", format!("getDirectory: {}", js_err(&e))))?;
        let handle: FileSystemDirectoryHandle = val
            .dyn_into()
            .map_err(|_| {
                Error::fs("getDirectory", "", "getDirectory: not a FileSystemDirectoryHandle")
            })?;
        // Cache in a brief, await-free borrow. Two concurrent first-init callers
        // each resolve their own `getDirectory()` (OPFS returns the same logical
        // root every time), so a double-init just caches the equivalent handle
        // twice — harmless, never a borrow conflict.
        *self.root.borrow_mut() = Some(handle.clone());
        Ok(handle)
    }

    /// Walk a path's parent components, returning the deepest directory
    /// handle and the final segment (`None` if the path resolves to the
    /// root itself).
    async fn resolve_parent(
        &self,
        path: &str,
        create_dirs: bool,
    ) -> Result<(FileSystemDirectoryHandle, Option<String>)> {
        let parts = split_path(path);
        if parts.is_empty() {
            return Ok((self.root_handle().await?, None));
        }
        let mut dir = self.root_handle().await?;
        for component in &parts[..parts.len() - 1] {
            dir = get_subdir(&dir, component, create_dirs).await?;
        }
        Ok((dir, Some(parts.last().unwrap().clone())))
    }

    /// Resolve a path to the directory handle it names (errors if the
    /// path doesn't exist or names a file).
    async fn resolve_dir(&self, path: &str) -> Result<FileSystemDirectoryHandle> {
        let parts = split_path(path);
        let mut dir = self.root_handle().await?;
        for component in &parts {
            dir = get_subdir(&dir, component, false).await?;
        }
        Ok(dir)
    }

    /// The main-thread `FileSystemWritableFileStream` write (non-WebKit
    /// engines, and the fallback when the broker is unsupported). Callers wrap
    /// it in [`bounded`] — never call it bare from the trait surface.
    async fn write_atomic_stream(&self, path: &str, bytes: &[u8]) -> Result<()> {
        let (parent, name) = self.resolve_parent(path, true).await?;
        let name = name.ok_or_else(|| {
            Error::fs("write_atomic", path, format!("write_atomic({path}): path is empty"))
        })?;
        let file_handle = get_file(&parent, &name, true).await?;
        let writable_val = JsFuture::from(file_handle.create_writable())
            .await
            .map_err(|e| {
                Error::fs("createWritable", path, format!("createWritable({path}): {}", js_err(&e)))
            })?;
        let writable: FileSystemWritableFileStream = writable_val
            .dyn_into()
            .map_err(|_| Error::fs("createWritable", path, "createWritable: not a writable stream"))?;
        // `Uint8Array::from(&[u8])` COPIES into a fresh standalone buffer
        // (byteOffset 0, length == payload). Never "optimize" this to
        // `Uint8Array::view` of wasm memory: WebKit bug 302733 (open through
        // Safari 26.4) ignores a view's byteOffset and writes the ENTIRE
        // underlying ArrayBuffer — for a wasm-memory view, the whole heap.
        let array = Uint8Array::from(bytes);
        let write_promise = writable
            .write_with_buffer_source(&array)
            .map_err(|e| Error::fs("write", path, format!("write({path}): {}", js_err(&e))))?;
        JsFuture::from(write_promise)
            .await
            .map_err(|e| Error::fs("write", path, format!("write({path}): {}", js_err(&e))))?;
        JsFuture::from(writable.close())
            .await
            .map_err(|e| Error::fs("close", path, format!("close({path}): {}", js_err(&e))))?;
        Ok(())
    }
}

/// Race `fut` against a wall-clock deadline. On timeout the abandoned future
/// is dropped mid-flight (its JS promise may still settle later — harmless);
/// the caller gets a typed error instead of a frozen app.
async fn bounded(
    ms: u32,
    op: &'static str,
    path: &str,
    fut: impl std::future::Future<Output = Result<()>>,
) -> Result<()> {
    use futures_util::future::{select, Either};
    match select(Box::pin(fut), Box::pin(crate::runtime::sleep_ms(ms))).await {
        Either::Left((res, _)) => res,
        Either::Right(((), _)) => Err(Error::fs(
            op,
            path,
            format!("{op}({path}): timed out after {ms}ms (engine OPFS stall) — data NOT saved"),
        )),
    }
}

// ---- WebKit write broker (the iOS fix) --------------------------------------
// web/opfs-worker.js performs writes via the worker-only
// `createSyncAccessHandle` (iOS 15.2+). The client here is feature-detected
// end-to-end: a spawn failure or an `unsupported` reply latches the broker
// DEAD and every write falls back to the bounded main-thread stream.

thread_local! {
    static BROKER: RefCell<Option<Broker>> = const { RefCell::new(None) };
    /// Sticky "stop trying the worker" latch (spawn failed / no sync API).
    static BROKER_DEAD: Cell<bool> = const { Cell::new(false) };
}

struct Broker {
    worker: Worker,
    /// id → the pending write's Promise `resolve`. Only ever borrowed in
    /// straight-line code — NEVER across an await (the RefCell-across-await
    /// iOS panic class; see `root_handle`).
    pending: Rc<RefCell<HashMap<u32, Function>>>,
    next_id: Cell<u32>,
    _onmessage: Closure<dyn FnMut(MessageEvent)>,
}

enum BrokerWrite {
    Done(Result<()>),
    /// This engine can't broker (no worker / no sync-access API) — caller
    /// falls through to the main-thread path. Latched, so it costs once.
    Unsupported,
}

/// WebKit detection: `navigator.vendor` is "Apple Computer, Inc." on Safari
/// AND every iOS browser shell (CriOS/FxiOS — WebKit is mandatory outside the
/// EU). `window.LH_FORCE_WORKER_FS = 1` forces the broker on any engine so
/// E2E can exercise it under Chromium (which has OPFS in automation).
fn engine_prefers_broker() -> bool {
    if BROKER_DEAD.with(Cell::get) {
        return false;
    }
    let Some(win) = web_sys::window() else { return false };
    if Reflect::get(&win, &JsValue::from_str("LH_FORCE_WORKER_FS"))
        .map(|v| v.is_truthy())
        .unwrap_or(false)
    {
        return true;
    }
    // `navigator.vendor` via Reflect (web-sys doesn't bind it): "Apple
    // Computer, Inc." on every WebKit shell; "Google Inc." on Chromium.
    Reflect::get(&win.navigator(), &JsValue::from_str("vendor"))
        .ok()
        .and_then(|v| v.as_string())
        .is_some_and(|v| v.starts_with("Apple"))
}

fn broker_spawn() -> Option<Broker> {
    let worker = Worker::new("/opfs-worker.js").ok()?;
    let pending: Rc<RefCell<HashMap<u32, Function>>> = Rc::new(RefCell::new(HashMap::new()));
    let map = Rc::clone(&pending);
    let onmessage = Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
        let data = e.data();
        let id = Reflect::get(&data, &JsValue::from_str("id"))
            .ok()
            .and_then(|v| v.as_f64())
            .unwrap_or(-1.0) as u32;
        let resolve = map.borrow_mut().remove(&id);
        if let Some(resolve) = resolve {
            let _ = resolve.call1(&JsValue::NULL, &data);
        }
    });
    worker.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
    Some(Broker { worker, pending, next_id: Cell::new(1), _onmessage: onmessage })
}

async fn broker_write(path: &str, bytes: &[u8]) -> BrokerWrite {
    // All setup is SYNCHRONOUS (spawn-if-needed, stash resolve, postMessage);
    // the only await is on the reply promise, outside every borrow.
    let fut = BROKER.with(|slot| {
        let mut slot = slot.borrow_mut();
        if slot.is_none() {
            *slot = broker_spawn();
        }
        let b = slot.as_ref()?;
        let id = b.next_id.get();
        b.next_id.set(id.wrapping_add(1));
        let pending = Rc::clone(&b.pending);
        let promise = Promise::new(&mut |resolve, _reject| {
            pending.borrow_mut().insert(id, resolve);
        });
        let msg = Object::new();
        let _ = Reflect::set(&msg, &JsValue::from_str("id"), &JsValue::from_f64(id as f64));
        let _ = Reflect::set(&msg, &JsValue::from_str("path"), &JsValue::from_str(path));
        // Fresh copy (byteOffset 0) — same bug-302733 rule as the stream path.
        let _ = Reflect::set(&msg, &JsValue::from_str("bytes"), &Uint8Array::from(bytes).buffer());
        if b.worker.post_message(&msg).is_err() {
            b.pending.borrow_mut().remove(&id);
            return None;
        }
        Some(JsFuture::from(promise))
    });
    let Some(fut) = fut else {
        BROKER_DEAD.with(|d| d.set(true));
        return BrokerWrite::Unsupported;
    };
    use futures_util::future::{select, Either};
    let reply = match select(Box::pin(fut), Box::pin(crate::runtime::sleep_ms(WRITE_TIMEOUT_MS)))
        .await
    {
        Either::Left((Ok(v), _)) => v,
        Either::Left((Err(e), _)) => {
            return BrokerWrite::Done(Err(Error::fs(
                "write_atomic",
                path,
                format!("write broker({path}): {}", js_err(&e)),
            )));
        }
        // Timed out: do NOT fall back (a late-settling worker write racing a
        // fallback write to the same file could corrupt it) and do NOT latch
        // (a slow-but-alive device shouldn't lose the broker forever).
        Either::Right(((), _)) => {
            return BrokerWrite::Done(Err(Error::fs(
                "write_atomic",
                path,
                format!("write broker({path}): timed out after {WRITE_TIMEOUT_MS}ms — data NOT saved"),
            )));
        }
    };
    let get = |k: &str| Reflect::get(&reply, &JsValue::from_str(k)).ok();
    if get("ok").and_then(|v| v.as_bool()) == Some(true) {
        return BrokerWrite::Done(Ok(()));
    }
    if get("unsupported").and_then(|v| v.as_bool()) == Some(true) {
        // No sync-access on this engine — latch + fall back (nothing was
        // written; the worker failed BEFORE touching the file).
        BROKER_DEAD.with(|d| d.set(true));
        return BrokerWrite::Unsupported;
    }
    let err = get("err").and_then(|v| v.as_string()).unwrap_or_else(|| "unknown".into());
    BrokerWrite::Done(Err(Error::fs("write_atomic", path, format!("write broker({path}): {err}"))))
}

#[async_trait(?Send)]
impl Filesystem for OpfsFilesystem {
    async fn read(&self, path: &str) -> Result<Vec<u8>> {
        let (parent, name) = self.resolve_parent(path, false).await?;
        let name =
            name.ok_or_else(|| Error::fs("read", path, format!("read({path}): path is empty")))?;
        let file_handle = get_file(&parent, &name, false).await?;
        let file_val = JsFuture::from(file_handle.get_file())
            .await
            .map_err(|e| Error::fs("getFile", path, format!("getFile({path}): {}", js_err(&e))))?;
        let file: File = file_val
            .dyn_into()
            .map_err(|_| Error::fs("getFile", path, format!("getFile({path}): not a File")))?;
        let buf = JsFuture::from(file.array_buffer())
            .await
            .map_err(|e| {
                Error::fs("arrayBuffer", path, format!("arrayBuffer({path}): {}", js_err(&e)))
            })?;
        let array = Uint8Array::new(&buf);
        Ok(array.to_vec())
    }

    async fn write_atomic(&self, path: &str, bytes: &[u8]) -> Result<()> {
        // WebKit engines (Safari, and EVERY iOS browser — CriOS/Firefox-iOS are
        // WebKit shells) broker writes through web/opfs-worker.js: Safari had
        // NO `createWritable` until Safari 26 (undefined on iOS ≤ 18 — the
        // 2026-06-18 "not available on iOS" gate), while the worker-only
        // `createSyncAccessHandle` has worked since iOS 15.2. One brokered
        // path covers iOS 15.2→26.x; `Unsupported` falls through to the
        // (timeout-bounded) main-thread stream below.
        if engine_prefers_broker() {
            match broker_write(path, bytes).await {
                BrokerWrite::Done(res) => return res,
                BrokerWrite::Unsupported => {}
            }
        }
        bounded(WRITE_TIMEOUT_MS, "write_atomic", path, self.write_atomic_stream(path, bytes))
            .await
    }

    async fn metadata(&self, path: &str) -> Result<Option<Metadata>> {
        let (parent, name) = self.resolve_parent(path, false).await?;
        let Some(name) = name else {
            // Path resolved to OPFS root — it's a directory.
            return Ok(Some(Metadata {
                kind: EntryKind::Directory,
                size: 0,
            }));
        };
        // Try file first, then directory.
        match get_file(&parent, &name, false).await {
            Ok(fh) => {
                let file_val = JsFuture::from(fh.get_file())
                    .await
                    .map_err(|e| Error::fs("getFile", path, format!("getFile({path}): {}", js_err(&e))))?;
                let file: File = file_val
                    .dyn_into()
                    .map_err(|_| Error::fs("getFile", path, format!("getFile({path}): not a File")))?;
                Ok(Some(Metadata {
                    kind: EntryKind::File,
                    size: file.size() as u64,
                }))
            }
            Err(_) => match get_subdir(&parent, &name, false).await {
                Ok(_) => Ok(Some(Metadata {
                    kind: EntryKind::Directory,
                    size: 0,
                })),
                Err(_) => Ok(None),
            },
        }
    }

    async fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>> {
        let dir = self.resolve_dir(path).await?;
        let mut entries = collect_entries(&dir).await?;
        entries.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(entries)
    }

    async fn walk(&self, path: &str, max_depth: Option<usize>) -> Result<Vec<WalkEntry>> {
        let root = self.resolve_dir(path).await?;
        let mut out = Vec::new();
        // Root entry itself at depth 0.
        out.push(WalkEntry {
            path: path.trim_end_matches('/').to_string(),
            kind: EntryKind::Directory,
            size: None,
        });
        walk_dir(&root, path, 1, max_depth, &mut out).await?;
        Ok(out)
    }

    async fn delete(&self, path: &str) -> Result<()> {
        let (parent, name) = self.resolve_parent(path, false).await?;
        let name =
            name.ok_or_else(|| {
                Error::fs("delete", path, format!("delete({path}): cannot delete OPFS root"))
            })?;
        let opts = FileSystemRemoveOptions::new();
        opts.set_recursive(true);
        let promise = parent.remove_entry_with_options(&name, &opts);
        JsFuture::from(promise)
            .await
            .map_err(|e| {
                Error::fs("removeEntry", path, format!("removeEntry({path}): {}", js_err(&e)))
            })?;
        Ok(())
    }
}

fn split_path(path: &str) -> Vec<String> {
    path.split('/')
        .filter(|s| !s.is_empty() && *s != ".")
        .map(|s| s.to_string())
        .collect()
}

async fn get_subdir(
    parent: &FileSystemDirectoryHandle,
    name: &str,
    create: bool,
) -> Result<FileSystemDirectoryHandle> {
    let opts = FileSystemGetDirectoryOptions::new();
    opts.set_create(create);
    let promise = parent.get_directory_handle_with_options(name, &opts);
    let val = JsFuture::from(promise)
        .await
        .map_err(|e| {
            Error::fs(
                "getDirectoryHandle",
                name,
                format!("getDirectoryHandle({name}): {}", js_err(&e)),
            )
        })?;
    val.dyn_into().map_err(|_| {
        Error::fs("getDirectoryHandle", name, format!("getDirectoryHandle({name}): wrong type"))
    })
}

async fn get_file(
    parent: &FileSystemDirectoryHandle,
    name: &str,
    create: bool,
) -> Result<FileSystemFileHandle> {
    let opts = FileSystemGetFileOptions::new();
    opts.set_create(create);
    let promise = parent.get_file_handle_with_options(name, &opts);
    let val = JsFuture::from(promise)
        .await
        .map_err(|e| {
            Error::fs("getFileHandle", name, format!("getFileHandle({name}): {}", js_err(&e)))
        })?;
    val.dyn_into()
        .map_err(|_| Error::fs("getFileHandle", name, format!("getFileHandle({name}): wrong type")))
}

/// Iterate a directory's entries via the JS async iterator protocol.
async fn collect_entries(dir: &FileSystemDirectoryHandle) -> Result<Vec<DirEntry>> {
    let iter_method =
        Reflect::get(dir, &JsValue::from_str("entries"))
            .map_err(|_| Error::fs("entries", "", "entries"))?;
    let iter_fn = iter_method
        .dyn_ref::<js_sys::Function>()
        .ok_or_else(|| Error::fs("entries", "", "entries() not callable"))?;
    let iterator = iter_fn
        .call0(dir)
        .map_err(|e| Error::fs("entries", "", format!("entries(): {}", js_err(&e))))?;
    let next_fn = Reflect::get(&iterator, &JsValue::from_str("next"))
        .map_err(|_| Error::fs("iterator.next", "", "iterator.next"))?
        .dyn_into::<js_sys::Function>()
        .map_err(|_| Error::fs("iterator.next", "", "iterator.next not a function"))?;

    let mut out = Vec::new();
    loop {
        let promise = next_fn
            .call0(&iterator)
            .map_err(|e| Error::fs("iterator.next", "", format!("iterator.next: {}", js_err(&e))))?;
        let result = JsFuture::from(js_sys::Promise::from(promise))
            .await
            .map_err(|e| {
                Error::fs("iterator await", "", format!("iterator await: {}", js_err(&e)))
            })?;
        let done = Reflect::get(&result, &JsValue::from_str("done"))
            .ok()
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        if done {
            break;
        }
        let value = Reflect::get(&result, &JsValue::from_str("value"))
            .map_err(|_| Error::fs("iterator value", "", "iterator value"))?;
        // value is [name, handle] tuple (a 2-element array).
        let pair: js_sys::Array = value
            .dyn_into()
            .map_err(|_| Error::fs("entries", "", "entry value not an array"))?;
        let name = pair
            .get(0)
            .as_string()
            .ok_or_else(|| Error::fs("entries", "", "entry[0] not a string"))?;
        let handle_val = pair.get(1);
        let handle: FileSystemHandle = handle_val
            .dyn_into()
            .map_err(|_| Error::fs("entries", "", "entry[1] not a FileSystemHandle"))?;
        let (kind, size) = match handle.kind() {
            FileSystemHandleKind::File => {
                let fh: FileSystemFileHandle = handle.unchecked_into();
                let file_val = JsFuture::from(fh.get_file())
                    .await
                    .map_err(|e| Error::fs("getFile", "", format!("getFile: {}", js_err(&e))))?;
                let file: File = file_val
                    .dyn_into()
                    .map_err(|_| Error::fs("getFile", "", "getFile: not a File"))?;
                (EntryKind::File, Some(file.size() as u64))
            }
            FileSystemHandleKind::Directory => (EntryKind::Directory, None),
            _ => (EntryKind::Other, None),
        };
        out.push(DirEntry { name, kind, size });
    }
    Ok(out)
}

/// Recursive depth-first walk. `depth` is the depth of `dir` relative
/// to the walk root (root itself is depth 0).
async fn walk_dir(
    dir: &FileSystemDirectoryHandle,
    prefix: &str,
    depth: usize,
    max_depth: Option<usize>,
    out: &mut Vec<WalkEntry>,
) -> Result<()> {
    if let Some(d) = max_depth {
        if depth > d {
            return Ok(());
        }
    }
    let entries = collect_entries(dir).await?;
    for entry in entries {
        // Stop once the global cap is hit (an over-large tree must not
        // exhaust memory) — matches NativeFilesystem's MAX_WALK_ENTRIES.
        if out.len() >= MAX_WALK_ENTRIES {
            return Ok(());
        }
        let path = if prefix.is_empty() || prefix == "/" {
            entry.name.clone()
        } else {
            format!("{}/{}", prefix.trim_end_matches('/'), entry.name)
        };
        match entry.kind {
            EntryKind::File => {
                out.push(WalkEntry {
                    path,
                    kind: EntryKind::File,
                    size: entry.size,
                });
            }
            EntryKind::Directory => {
                out.push(WalkEntry {
                    path: path.clone(),
                    kind: EntryKind::Directory,
                    size: None,
                });
                let sub = get_subdir(dir, &entry.name, false).await?;
                // Recursive async — use Box::pin to avoid infinite future size.
                Box::pin(walk_dir(&sub, &path, depth + 1, max_depth, out)).await?;
            }
            _ => {
                out.push(WalkEntry {
                    path,
                    kind: entry.kind,
                    size: entry.size,
                });
            }
        }
    }
    Ok(())
}

/// Best-effort stringify of a JsValue error.
fn js_err(e: &JsValue) -> String {
    if let Some(s) = e.as_string() {
        return s;
    }
    if let Ok(name) = Reflect::get(e, &JsValue::from_str("name")) {
        if let Ok(msg) = Reflect::get(e, &JsValue::from_str("message")) {
            return format!(
                "{}: {}",
                name.as_string().unwrap_or_default(),
                msg.as_string().unwrap_or_default()
            );
        }
    }
    // Fall back to the Object.prototype.toString form.
    let obj: Object = e.clone().unchecked_into();
    obj.to_string().as_string().unwrap_or_else(|| "<js error>".into())
}