localharness 0.30.0

A Rust-native agent SDK with pluggable LLM backends (Gemini today). Streaming, custom tools, safety policies, background triggers — zero external binaries.
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
//! Admin panel — config handlers (prompt / allowlist / api key / x402 price)
//! plus the header dropdown shell, tabs, and usage slot.

use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;

use crate::app::{dom, templates};

/// Persist the textarea content as the per-origin custom system
/// prompt. Empty/whitespace-only content deletes the file, reverting
/// to the bundle's default. The change takes effect on the next
/// session start — surfaced inline so the user knows what to expect.
pub(super) fn save_prompt_pressed() {
    let Some(textarea) = dom::textarea_by_id("prompt-input") else { return };
    let content = textarea.value();
    dom::swap_inner(
        "prompt-msg",
        "<span style=\"color:var(--muted)\">saving…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        match crate::app::system_prompt::save(&content).await {
            Ok(()) => {
                let trimmed = content.trim();
                let summary = if trimmed.is_empty() {
                    "✓ saved · using default on next session"
                } else {
                    "✓ saved · takes effect on next session"
                };
                dom::swap_inner(
                    "prompt-msg",
                    &dom::msg_span(dom::Msg::Accent, summary),
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "prompt-msg",
                    &dom::msg_span(dom::Msg::Error, &err.to_string()),
                );
            }
        }
    });
}

pub(super) fn save_tool_allowlist_pressed() {
    use crate::types::BuiltinTool;
    let mut enabled = Vec::new();
    if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
        if let Ok(checkboxes) = doc.query_selector_all(".tool-checkbox") {
            for i in 0..checkboxes.length() {
                if let Some(el) = checkboxes.get(i) {
                    let input: web_sys::HtmlInputElement = JsCast::unchecked_into(el);
                    if input.checked() {
                        if let Some(name) = input.get_attribute("data-tool") {
                            if let Some(tool) = BuiltinTool::ALL.iter().find(|t| t.wire_name() == name) {
                                enabled.push(*tool);
                            }
                        }
                    }
                }
            }
        }
    }
    dom::swap_inner(
        "tool-allowlist-msg",
        "<span style=\"color:var(--muted)\">saving…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        match crate::app::tool_allowlist::save(&enabled).await {
            Ok(()) => {
                let summary = crate::app::tool_allowlist::summary(&enabled);
                dom::swap_inner(
                    "tool-allowlist-msg",
                    &dom::msg_span(dom::Msg::Accent, &format!("✓ saved · {summary} · takes effect on next session")),
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "tool-allowlist-msg",
                    &dom::msg_span(dom::Msg::Error, &err.to_string()),
                );
            }
        }
    });
}

pub(super) fn reset_tool_allowlist_pressed() {
    dom::swap_inner(
        "tool-allowlist-msg",
        "<span style=\"color:var(--muted)\">resetting…</span>",
    );
    if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
        if let Ok(checkboxes) = doc.query_selector_all(".tool-checkbox") {
            for i in 0..checkboxes.length() {
                if let Some(el) = checkboxes.get(i) {
                    let input: web_sys::HtmlInputElement = JsCast::unchecked_into(el);
                    input.set_checked(true);
                }
            }
        }
    }
    wasm_bindgen_futures::spawn_local(async move {
        match crate::app::tool_allowlist::save(&[]).await {
            Ok(()) => {
                dom::swap_inner(
                    "tool-allowlist-msg",
                    "<span style=\"color:var(--accent)\">✓ reset · all tools enabled · takes effect on next session</span>",
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "tool-allowlist-msg",
                    &dom::msg_span(dom::Msg::Error, &err.to_string()),
                );
            }
        }
    });
}

/// Save the API key from the centered modal, then dismiss the modal.
pub(super) fn save_api_key_pressed() {
    let Some(input) = dom::input_by_id("api-key-input") else { return };
    let value = input.value().trim().to_string();
    if value.is_empty() {
        return;
    }
    if let Ok(Some(storage)) = dom::session_storage() {
        let _ = storage.set_item("gemini_api_key", &value);
    }
    dom::swap_inner(
        "api-key-msg",
        "<span style=\"color:var(--muted)\">checking…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        crate::app::key_store::save(&value).await;
        crate::app::opfs::refresh().await;
        // Validate against Gemini so a bad key is caught here, not
        // mid-turn. A definitive rejection keeps the modal open; a valid
        // key OR an inconclusive check (network/CORS) closes it — we
        // never block the user on a flaky probe.
        if let Some(false) = gemini_key_is_valid(&value).await {
            dom::swap_inner(
                "api-key-msg",
                "<span style=\"color:var(--error)\">key rejected — check it</span>",
            );
            return;
        }
        if let Some(el) = dom::by_id("api-key-modal") {
            if let Some(parent) = el.parent_element() {
                let _ = parent.remove_child(&el);
            }
        }
        // Auto-sync to the MAIN slot on-chain (best-effort, seed-bearing
        // devices only) so other subdomains + linked devices pick it up
        // without re-entry. Fire-and-forget after the modal closes.
        if let Some(name) = crate::app::tenant::current_name() {
            super::key_sync::auto_sync_gemini_key(name, value).await;
        }
    });
}

/// Probe whether a Gemini API key works via a cheap `models.list` GET
/// (no token cost). `Some(true/false)` is definitive; `None` means the
/// check was inconclusive (network/CORS) and the caller should not block
/// on it. Browser→Gemini CORS is already proven by the chat path.
async fn gemini_key_is_valid(key: &str) -> Option<bool> {
    let url = format!("https://generativelanguage.googleapis.com/v1beta/models?key={key}");
    match reqwest::Client::new().get(&url).send().await {
        Ok(resp) => Some(resp.status().is_success()),
        Err(_) => None,
    }
}

/// Save this agent's per-call x402 price (whole `$LH` → wei in
/// `.lh_x402_price`). Empty / 0 deletes the file (free).
pub(super) fn save_x402_price_pressed() {
    let Some(input) = dom::input_by_id("x402-price-input") else {
        return;
    };
    let raw = input.value().trim().to_string();
    wasm_bindgen_futures::spawn_local(async move {
        use crate::filesystem::Filesystem;
        let fs = crate::app::shared_opfs();
        let result: Result<(), String> = async {
            if raw.is_empty() || raw == "0" {
                let _ = fs.delete(".lh_x402_price").await;
                return Ok(());
            }
            let whole: u128 = raw.parse().map_err(|_| "bad amount".to_string())?;
            let wei = whole
                .checked_mul(1_000_000_000_000_000_000u128)
                .ok_or_else(|| "overflow".to_string())?;
            fs.write_atomic(".lh_x402_price", wei.to_string().as_bytes())
                .await
                .map_err(|e| e.to_string())
        }
        .await;
        match result {
            Ok(()) => dom::swap_inner(
                "x402-price-msg",
                "<span style=\"color:var(--muted)\">saved</span>",
            ),
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("x402 price: {e}")));
                dom::swap_inner(
                    "x402-price-msg",
                    "<span style=\"color:var(--error)\">save failed</span>",
                );
            }
        }
    });
}

/// Toggle the header admin dropdown. Origin determines content —
/// apex shows seed reveal + import + reset, tenant has the gemini
/// api key input + reset. After opening, pre-fill the api key from
/// sessionStorage / OPFS so the user sees their existing key
/// (admin opens and closes constantly; the input is fresh DOM each time).
pub(super) fn header_admin_toggle() {
    let body = match crate::app::tenant::current() {
        crate::app::tenant::Host::Apex => templates::admin_dropdown_apex().into_string(),
        crate::app::tenant::Host::Tenant(_) | crate::app::tenant::Host::Other(_) => {
            templates::admin_dropdown_tenant().into_string()
        }
    };
    dom::swap_outer("header-admin-panel", &body);

    // Inject the stashed agent card (folded in from the retired right rail)
    // into the Account tab's #financial-slot. Built by kick_verification.
    if let Some(card) = crate::app::APP.with(|c| c.borrow().financial_card_html.clone()) {
        if dom::by_id("financial-slot").is_some() {
            dom::swap_outer("financial-slot", &card);
        }
    }

    // Fill the Usage tab's subdomain count + token total. No-ops if the
    // slots aren't there.
    wasm_bindgen_futures::spawn_local(async move {
        refresh_usage_slot().await;
    });

    // Credit balance — on EVERY host (apex AND subdomains). Credits are
    // master-EOA-scoped, so a subdomain shows the SAME balance as the apex; the
    // old apex-only gate is exactly why subdomains showed a blank "…" / "—".
    // Fire-and-forget so the dropdown paints immediately; the pill resolves from
    // "…" to "N LH".
    wasm_bindgen_futures::spawn_local(async move {
        super::refresh_credits_pill().await;
    });
    // Recurring jobs list (ScheduleFacet) — no-ops if the slot isn't mounted
    // (no wallet) or no identity exists yet. Same fire-and-forget shape as
    // the credits pill so the dropdown paints immediately.
    wasm_bindgen_futures::spawn_local(async move {
        super::schedule::refresh_jobs_list().await;
    });
    // Open bounties list (BountyFacet) — same fire-and-forget shape; no-ops if
    // the slot isn't mounted (no wallet).
    wasm_bindgen_futures::spawn_local(async move {
        super::bounty::refresh_bounty_list().await;
    });
    // The caller's guilds (GuildFacet) — same fire-and-forget shape; no-ops if
    // the slot isn't mounted (no wallet) or no identity exists yet.
    wasm_bindgen_futures::spawn_local(async move {
        super::guild::refresh_guild_list().await;
    });
    // Device/signer management lives at the apex only.
    if matches!(crate::app::tenant::current(), crate::app::tenant::Host::Apex) {
        wasm_bindgen_futures::spawn_local(async move {
            super::devices::refresh_signer_list().await;
        });
    }

    // Pre-fill api key from sessionStorage (sync) then refresh from
    // OPFS (async). Same pattern as the old in-chrome key restore.
    if matches!(
        crate::app::tenant::current(),
        crate::app::tenant::Host::Tenant(_) | crate::app::tenant::Host::Other(_)
    ) {
        if let Ok(Some(storage)) = dom::session_storage() {
            if let Ok(Some(cached)) = storage.get_item("gemini_api_key") {
                if let Some(input) = dom::input_by_id("key") {
                    input.set_value(&cached);
                    super::refresh_keymeta();
                }
            }
        }
        wasm_bindgen_futures::spawn_local(async move {
            if let Some(persisted) = crate::app::key_store::load().await {
                if let Some(input) = dom::input_by_id("key") {
                    input.set_value(&persisted);
                    super::refresh_keymeta();
                }
            }
            // Restore the saved custom prompt into the textarea so the
            // user can edit instead of re-typing.
            if let Some(prompt) = crate::app::system_prompt::load().await {
                if let Some(textarea) = dom::textarea_by_id("prompt-input") {
                    textarea.set_value(&prompt);
                }
            }
            // Prefill the x402 price (stored as wei → shown as whole LH).
            {
                use crate::filesystem::Filesystem;
                if let Ok(bytes) = crate::app::shared_opfs().read(".lh_x402_price").await {
                    if let Some(wei) = String::from_utf8(bytes)
                        .ok()
                        .and_then(|s| s.trim().parse::<u128>().ok())
                    {
                        if let Some(input) = dom::input_by_id("x402-price-input") {
                            input.set_value(&(wei / 1_000_000_000_000_000_000u128).to_string());
                        }
                    }
                }
            }
            if let Some(allowed) = crate::app::tool_allowlist::load().await {
                if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
                    if let Ok(checkboxes) = doc.query_selector_all(".tool-checkbox") {
                        for i in 0..checkboxes.length() {
                            if let Some(el) = checkboxes.get(i) {
                                let input: web_sys::HtmlInputElement = JsCast::unchecked_into(el);
                                if let Some(name) = input.get_attribute("data-tool") {
                                    let is_allowed = allowed.iter().any(|t| t.wire_name() == name);
                                    input.set_checked(is_allowed);
                                }
                            }
                        }
                    }
                }
                let summary = crate::app::tool_allowlist::summary(&allowed);
                dom::swap_inner("tool-allowlist-status", &summary);
            } else {
                dom::swap_inner("tool-allowlist-status", "all tools enabled");
            }
            refresh_public_face_status().await;
            super::credits::refresh_model_selector().await;
        });
    }
}

/// Read the subdomain's current on-chain public-face choice and reflect it
/// in the `#public-face-status` slot. No-op off a tenant or if the slot
/// isn't mounted.
pub(super) async fn refresh_public_face_status() {
    let Some(name) = crate::app::tenant::current_name() else { return };
    if dom::by_id("public-face-status").is_none() {
        return;
    }
    // Timeout-capped so a dead RPC resolves to the directory-default label
    // instead of leaving the placeholder text up forever.
    let face = match crate::app::net::read(crate::app::registry::id_of_name(&name)).await {
        Ok(Ok(id)) if id != 0 => crate::app::net::read(crate::app::registry::public_face_of(id))
            .await
            .ok()
            .and_then(Result::ok)
            .flatten(),
        _ => None,
    };
    let label = match face.as_deref() {
        Some("app") => "currently: app",
        Some("html") => "currently: html",
        _ => "currently: directory (default)",
    };
    dom::swap_inner("public-face-status", label);
}

pub(super) fn header_admin_close() {
    dom::swap_outer(
        "header-admin-panel",
        r#"<div id="header-admin-panel" hidden></div>"#,
    );
}

/// Switch the active admin tab by flipping the `tab-<name>` class on
/// `#admin-dialog` (CSS shows the matching `.panel-<name>`), and sync the
/// `.active` state on the tab buttons. Mirrors `show_mobile_tab`.
pub(super) fn show_admin_tab(name: &str) {
    let Some(dialog) = dom::by_id("admin-dialog") else { return };
    let mut cls: Vec<String> = dialog
        .class_name()
        .split_whitespace()
        .filter(|c| !c.starts_with("tab-"))
        .map(String::from)
        .collect();
    cls.push(format!("tab-{name}"));
    dialog.set_class_name(&cls.join(" "));

    for tab in ["agent", "account", "usage", "feedback"] {
        let Some(el) = dom::by_id(&format!("admin-tab-btn-{tab}")) else { continue };
        let c = el.class_name();
        let mut classes: Vec<&str> = c.split_whitespace().filter(|x| *x != "active").collect();
        if tab == name {
            classes.push("active");
        }
        el.set_class_name(&classes.join(" "));
    }
}

/// Fill the admin Usage tab's `#usage-subdomains` slot with the on-chain
/// registered-subdomain count. Soft-fail (leaves a dash). No-op if the
/// slot isn't present.
pub(crate) async fn refresh_usage_slot() {
    // Tokens — synchronous read from App state (updated after each turn).
    if dom::by_id("usage-tokens").is_some() {
        let total = crate::app::APP.with(|c| c.borrow().total_tokens);
        dom::swap_inner("usage-tokens", &format!("{total}"));
    }
    if dom::by_id("usage-subdomains").is_none() {
        return;
    }
    // YOUR owned subdomains — NOT the global registry total. `subdomain_count`
    // (nextId-1) counts every name ever minted, including released/burned ones,
    // so after a reset it stays high (the "still says 30" bug). Resolve the
    // owner from the current tenant (else the local wallet) and count what they
    // actually hold (released ids have ownerOfId=0, so they drop out).
    let owner = match crate::app::tenant::current() {
        crate::app::tenant::Host::Tenant(name) => {
            crate::app::registry::owner_of_name(&name).await.ok().flatten()
        }
        _ => crate::app::APP.with(|c| c.borrow().wallet.as_ref().map(|w| w.address_hex())),
    };
    let count = match owner {
        Some(owner_hex) => crate::app::registry::list_owned_tokens(&owner_hex)
            .await
            .map(|t| t.len()),
        None => Ok(0),
    };
    match count {
        Ok(n) => dom::swap_inner("usage-subdomains", &format!("{n}")),
        Err(_) => dom::swap_inner("usage-subdomains", ""),
    }
}

/// Mobile-only: swap which `tab-<name>` class is on `#layout`.
/// CSS uses it to show exactly one panel at a time on narrow
/// viewports. Tab button styling syncs by toggling `.active`.
pub(super) fn show_mobile_tab(name: &str) {
    let Some(layout) = dom::by_id("layout") else { return };
    let parts: Vec<String> = layout
        .class_name()
        .split_whitespace()
        .filter(|c| !c.starts_with("tab-"))
        .map(String::from)
        .collect();
    let mut new_cls = parts.join(" ");
    if !new_cls.is_empty() {
        new_cls.push(' ');
    }
    new_cls.push_str(&format!("tab-{name}"));
    layout.set_class_name(&new_cls);

    // The display tab shows the framebuffer; mount an idle surface if
    // nothing is already on it so the canvas exists when the tab opens.
    if name == "display" && dom::by_id("display-canvas").is_none() {
        dom::swap_inner(
            "view-content",
            &crate::app::templates::display_surface().into_string(),
        );
    }

    // Reflect active state on each tab button by id — small fixed
    // set of tabs, no need for query_selector_all (which needs the
    // NodeList web-sys feature we don't enable).
    for tab in ["files", "chat", "display", "agent"] {
        let id = format!("tab-btn-{tab}");
        let Some(el) = dom::by_id(&id) else { continue };
        let cls = el.class_name();
        let mut classes: Vec<&str> =
            cls.split_whitespace().filter(|c| *c != "active").collect();
        if tab == name {
            classes.push("active");
        }
        el.set_class_name(&classes.join(" "));
    }
}