localharness 0.35.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
//! Notifications + Web Push (browser-app).
//!
//! Two surfaces share this module:
//!   * the agent's `notify(title, body?, vibrate?)` closure tool
//!     (`chat::tools::misc::notify_tool`) — in-tab notifications/vibration
//!     for alarms, message-arrived, job-done;
//!   * the admin "notifications" row (`Action::EnableNotifications`) —
//!     subscribes Web Push and publishes the subscription JSON on-chain so
//!     the proxy's scheduler worker can notify the owner with the tab CLOSED
//!     (`proxy/api/scheduler.ts` reads it back per job owner).
//!
//! Notifications are shown through the SERVICE-WORKER registration when one
//! exists (`registration.showNotification`) — the page-level
//! `new Notification(...)` constructor throws in a document context on
//! Android, so the SW path is the one that works everywhere. `web/sw.js` is
//! registered by `boot.js` at boot; `subscribe_push` re-registers it
//! idempotently before subscribing.

use std::cell::RefCell;

use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;

thread_local! {
    /// In-app notification bell log (newest first, capped). The header
    /// `#notif-bell-panel` renders from this; `#notif-bell-badge` shows the
    /// unread count. Fed by READY-UP broadcasts (the presser's own ding) and
    /// service-worker pushes relayed to the open page (boot.js `lh-push`).
    /// Persisted to OPFS so the inbox survives reloads.
    static BELL: RefCell<Vec<(String, String)>> = const { RefCell::new(Vec::new()) };
}

/// The persisted inbox (written by [`push_to_bell`], read at mount).
const INBOX_FILE: &str = ".lh_notif_inbox.json";
/// Pushes that arrived with NO page open, stashed by `web/sw.js` directly in
/// OPFS; merged + deleted by [`load_inbox`] at the next boot.
const PENDING_FILE: &str = ".lh_notif_pending.json";

/// Append a notification to the in-app header bell (newest first, cap 30),
/// bump the unread badge, and persist the inbox. The panel re-render keeps
/// its CURRENT visibility — a push landing mid-read must not yank the
/// dropdown shut (or open it uninvited).
pub(crate) fn push_to_bell(title: &str, body: &str) {
    BELL.with(|b| {
        let mut v = b.borrow_mut();
        v.insert(0, (title.to_string(), body.to_string()));
        v.truncate(30);
    });
    let n = BELL.with(|b| b.borrow().len());
    crate::app::dom::swap_outer(
        "notif-bell-badge",
        &format!("<span id=\"notif-bell-badge\" class=\"notif-badge\">{n}</span>"),
    );
    let hidden = crate::app::dom::by_id("notif-bell-panel")
        .map(|e| e.has_attribute("hidden"))
        .unwrap_or(true);
    crate::app::dom::swap_outer(
        "notif-bell-panel",
        &crate::app::templates::notif_list_panel(&bell_items(), None, hidden).into_string(),
    );
    wasm_bindgen_futures::spawn_local(persist_inbox());
}

/// Service-worker push relay (boot.js → the `push_arrived` wasm export):
/// a Web Push that arrived while this page is open lands in the bell inbox.
pub(crate) fn push_arrived(title: &str, body: &str) {
    let title = if title.is_empty() { "localharness" } else { title };
    push_to_bell(title, body);
}

/// Persist the bell log to OPFS (best-effort; logs, never surfaces).
async fn persist_inbox() {
    let items = bell_items();
    let Ok(bytes) = serde_json::to_vec(&items) else { return };
    let fs = crate::app::shared_opfs();
    if let Err(e) = fs.write_atomic(INBOX_FILE, &bytes).await {
        web_sys::console::warn_1(&JsValue::from_str(&format!("notif inbox save: {e}")));
    }
}

/// Restore the bell inbox at mount: closed-tab pushes stashed by the service
/// worker (newest, still unread) first, then the persisted log from the last
/// session. The unread badge counts ONLY the stashed arrivals — a reload must
/// not re-flag entries the user already saw.
pub(crate) async fn load_inbox() {
    let fs = crate::app::shared_opfs();
    let mut items: Vec<(String, String)> = Vec::new();
    if let Ok(b) = fs.read(PENDING_FILE).await {
        if let Ok(mut v) = serde_json::from_slice::<Vec<(String, String)>>(&b) {
            items.append(&mut v);
        }
        let _ = fs.delete(PENDING_FILE).await;
    }
    let fresh = items.len();
    if let Ok(b) = fs.read(INBOX_FILE).await {
        if let Ok(mut v) = serde_json::from_slice::<Vec<(String, String)>>(&b) {
            items.append(&mut v);
        }
    }
    if items.is_empty() {
        return;
    }
    items.truncate(30);
    BELL.with(|b| *b.borrow_mut() = items);
    if fresh > 0 {
        crate::app::dom::swap_outer(
            "notif-bell-badge",
            &format!("<span id=\"notif-bell-badge\" class=\"notif-badge\">{fresh}</span>"),
        );
        persist_inbox().await; // fold the drained pending file into the log
    }
    crate::app::dom::swap_outer(
        "notif-bell-panel",
        &crate::app::templates::notif_list_panel(&bell_items(), None, true).into_string(),
    );
}

/// Snapshot of the in-app bell log (newest first).
pub(crate) fn bell_items() -> Vec<(String, String)> {
    BELL.with(|b| b.borrow().clone())
}

/// Hide the unread badge (called when the bell panel is opened / read).
pub(crate) fn clear_bell_badge() {
    crate::app::dom::swap_outer(
        "notif-bell-badge",
        "<span id=\"notif-bell-badge\" class=\"notif-badge\" hidden></span>",
    );
}

/// VAPID application-server PUBLIC key (base64url, uncompressed P-256 point)
/// — the `applicationServerKey` for `PushManager.subscribe`, pair of the
/// proxy's `VAPID_PRIVATE_KEY`.
///
/// MAINTAINER: this key was generated for this feature branch; the matching
/// private key must be set on the PROXY Vercel project as
/// `VAPID_PRIVATE_KEY` (plus `VAPID_PUBLIC_KEY` = this value and
/// `VAPID_SUBJECT`, e.g. `mailto:compusophy@gmail.com`). Replace BOTH halves
/// together if you rotate — existing on-chain subscriptions die with the key.
pub(crate) const VAPID_PUBLIC_KEY: &str =
    "BHtamLu5RHqMWbV3JyyEmQKL-lweTVq3ePiFOHGu_EBzvrz4w0SzpWpBTI02UgWOkFR9sbAqPrvj8LOtF5R5jow";

fn js_err(context: &str, e: JsValue) -> String {
    format!("{context}: {}", e.as_string().unwrap_or_else(|| format!("{e:?}")))
}

fn window() -> Result<web_sys::Window, String> {
    web_sys::window().ok_or_else(|| "no window".to_string())
}

/// Current Notification permission, requesting it if undecided. `Ok(true)` =
/// granted. Browsers may auto-deny a request outside a user gesture — the
/// admin [enable notifications] button is the gesture path; the agent tool
/// degrades to a permission report.
pub(crate) async fn ensure_permission() -> Result<bool, String> {
    use web_sys::{Notification, NotificationPermission};
    match Notification::permission() {
        NotificationPermission::Granted => return Ok(true),
        NotificationPermission::Denied => return Ok(false),
        _ => {}
    }
    let promise = Notification::request_permission().map_err(|e| js_err("requestPermission", e))?;
    let result = JsFuture::from(promise)
        .await
        .map_err(|e| js_err("requestPermission", e))?;
    Ok(result.as_string().as_deref() == Some("granted"))
}

/// The current service-worker registration, if any (resolves `undefined`
/// when boot.js hasn't registered / SW unsupported).
async fn sw_registration() -> Option<web_sys::ServiceWorkerRegistration> {
    let sw = web_sys::window()?.navigator().service_worker();
    let v = JsFuture::from(sw.get_registration()).await.ok()?;
    v.dyn_into::<web_sys::ServiceWorkerRegistration>().ok()
}

/// Show a notification (caller has already ensured permission). Prefers the
/// service-worker registration; falls back to the page constructor where no
/// SW exists (desktop without sw.js — e.g. localhost dev).
pub(crate) async fn show(title: &str, body: &str) -> Result<(), String> {
    let opts = web_sys::NotificationOptions::new();
    opts.set_body(body);
    opts.set_icon("/icons/icon-192.png");
    // Same-content notifications COLLAPSE instead of stacking (Android
    // shows untagged notifications separately — feedback #55 reported
    // doubles): tag = the content itself, so an accidental second render
    // replaces the first instead of buzzing twice.
    opts.set_tag(&format!("lh-{title}-{body}"));
    if let Some(reg) = sw_registration().await {
        let promise = reg
            .show_notification_with_options(title, &opts)
            .map_err(|e| js_err("showNotification", e))?;
        JsFuture::from(promise)
            .await
            .map_err(|e| js_err("showNotification", e))?;
        return Ok(());
    }
    web_sys::Notification::new_with_options(title, &opts)
        .map(|_| ())
        .map_err(|e| js_err("Notification", e))
}

/// Vibrate the device for `ms` milliseconds. Best-effort: returns false where
/// unsupported (desktop) or blocked (no user activation) — never errors.
pub(crate) fn vibrate(ms: u32) -> bool {
    match web_sys::window() {
        Some(win) => win.navigator().vibrate_with_duration(ms),
        None => false,
    }
}

/// Subscribe this browser to Web Push (registering `sw.js` if needed) and
/// return the subscription JSON (`{endpoint, keys: {p256dh, auth}}`) — the
/// exact shape the proxy's push sender consumes.
pub(crate) async fn subscribe_push() -> Result<String, String> {
    let container = window()?.navigator().service_worker();
    // Idempotent re-register: boot.js already did this on a normal boot, but
    // an old tab from before the SW shipped (or a failed first attempt)
    // would otherwise hang on `ready` forever.
    let _ = JsFuture::from(container.register("/sw.js")).await;
    let ready = container.ready().map_err(|e| js_err("serviceWorker.ready", e))?;
    let reg: web_sys::ServiceWorkerRegistration = JsFuture::from(ready)
        .await
        .map_err(|e| js_err("serviceWorker.ready", e))?
        .dyn_into()
        .map_err(|_| "serviceWorker.ready: not a registration".to_string())?;
    let manager = reg.push_manager().map_err(|e| js_err("pushManager", e))?;

    let opts = web_sys::PushSubscriptionOptionsInit::new();
    opts.set_user_visible_only(true);
    let key_bytes = {
        use base64::Engine as _;
        base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(VAPID_PUBLIC_KEY)
            .map_err(|e| format!("bad VAPID_PUBLIC_KEY constant: {e}"))?
    };
    let key_js: JsValue = js_sys::Uint8Array::from(key_bytes.as_slice()).into();
    opts.set_application_server_key(&key_js);

    let sub: web_sys::PushSubscription = JsFuture::from(
        manager
            .subscribe_with_options(&opts)
            .map_err(|e| js_err("push subscribe", e))?,
    )
    .await
    .map_err(|e| js_err("push subscribe", e))?
    .dyn_into()
    .map_err(|_| "push subscribe: not a PushSubscription".to_string())?;

    // PushSubscription has a toJSON, so JSON.stringify yields the canonical
    // {endpoint, expirationTime, keys} shape.
    js_sys::JSON::stringify(&sub)
        .map_err(|e| js_err("subscription stringify", e))?
        .as_string()
        .ok_or_else(|| "subscription stringify: empty".to_string())
}

/// The admin [enable notifications] flow: permission → push subscription →
/// publish the subscription JSON on-chain under
/// `keccak256("localharness.push_sub")` for the owner's MAIN tokenId
/// (fallback: this name's own id — mirrors the Gemini-key-sync slot rule, so
/// ONE subscription serves every subdomain of the identity). Sponsored write,
/// zero-click. Returns the tx hash.
///
/// KNOWN TRADEOFF (v1): the subscription is stored PLAINTEXT on-chain. The
/// endpoint is a bearer capability URL — anyone reading chain state can send
/// this device (unauthenticated-origin) pushes until the user unsubscribes.
/// Payloads are still E2E-encrypted to this browser (p256dh/auth), so no
/// third party can read OUR pushes; the exposure is spam/identification.
/// Follow-up: ECIES-seal the JSON to a proxy-held key so only the scheduler
/// can read it.
/// Enable Web Push for THIS DEVICE keyed by its OWN ADDRESS (PushFacet), not a
/// MAIN tokenId — so ANY visitor (a bare device key, `mainOf == 0`) can receive
/// cross-device pushes. MUST be called from a DIRECT user gesture (the header
/// notification bell): the cartridge subscribe tap runs through a worker
/// postMessage that loses user activation, so its `requestPermission` never
/// prompts on mobile and the device silently never registers — THE
/// cross-device-push bug. This path prompts, subscribes, and publishes the
/// address-keyed subscription (signed by the device's credit key, sponsored).
/// Returns the tx hash. Idempotent — safe to tap again to refresh a stale sub.
pub(crate) async fn enable_device_push() -> Result<String, String> {
    if !ensure_permission().await? {
        return Err("notification permission is blocked — allow notifications for this site in your browser settings, then tap again".to_string());
    }
    let sub_json = subscribe_push().await?;
    let (signer, addr) = crate::app::chat::credit_signer()
        .await
        .ok_or_else(|| "no identity on this device yet".to_string())?;
    // MULTI-DEVICE: merge into the existing slot (array, upsert by endpoint)
    // instead of overwriting — a phone and a desktop share this address (same
    // seed), and a bare replace silently de-registered the other device.
    let addr_hex = crate::encoding::bytes_to_hex_str(&addr);
    let slot = crate::registry::addr_push_sub_of(&addr_hex).await.ok().flatten();
    let Some(merged) = crate::registry::merge_push_sub(slot.as_deref(), &sub_json) else {
        return Ok("already registered".to_string());
    };
    let sponsor = crate::app::sponsor::signer().map_err(|e| format!("sponsor: {e}"))?;
    let token = crate::registry::ALPHA_USD_ADDRESS;
    crate::registry::set_push_sub_sponsored(&signer, &sponsor, merged.as_bytes(), token).await
}

pub(crate) async fn enable_and_publish() -> Result<String, String> {
    if !ensure_permission().await? {
        return Err("notification permission denied — allow notifications for this site in the browser settings".to_string());
    }
    let sub_json = subscribe_push().await?;

    let (name, owner) = crate::app::tenant::current_tenant_owner().await?;
    let token_id = match crate::registry::main_of(&owner).await {
        Ok(id) if id != 0 => id,
        _ => match crate::registry::id_of_name(&name).await {
            Ok(id) if id != 0 => id,
            Ok(_) => return Err("this subdomain isn't registered on-chain yet".to_string()),
            Err(e) => return Err(format!("id_of_name: {e}")),
        },
    };

    // MULTI-DEVICE merge (see enable_device_push) — never overwrite siblings.
    let slot = crate::registry::push_sub_of(token_id).await.ok().flatten();
    let Some(merged) = crate::registry::merge_push_sub(slot.as_deref(), &sub_json) else {
        return Ok("already registered".to_string());
    };

    let registry_addr = crate::encoding::parse_address(crate::registry::REGISTRY_ADDRESS)?;
    let call = crate::tempo_tx::TempoCall {
        to: registry_addr,
        value_wei: 0,
        input: crate::registry::encode_set_push_sub(token_id, merged.as_bytes()),
    };
    let gas = crate::app::gas::set_metadata_gas(merged.len());
    crate::app::events::run_sponsored_tempo_call(&owner, vec![call], gas, "publish push subscription")
        .await
}

/// Silently refresh a STALE push subscription on app open. Reinstalling the
/// PWA / clearing site data invalidates the browser's old push endpoint, but
/// the on-chain slot keeps serving it — every worker push then dies with an
/// FCM 410 and the owner silently stops getting buzzed (seen live 2026-06-12).
/// When permission is already granted, re-subscribe (idempotent) and, if the
/// endpoint differs from the published one, re-publish. Best-effort: any
/// failure leaves the existing state untouched; never prompts.
pub(crate) async fn refresh_subscription_if_stale() {
    if !matches!(
        web_sys::Notification::permission(),
        web_sys::NotificationPermission::Granted
    ) {
        return;
    }
    let Ok(current) = subscribe_push().await else {
        return;
    };
    let Ok((name, owner)) = crate::app::tenant::current_tenant_owner().await else {
        return;
    };
    let token_id = match crate::registry::main_of(&owner).await {
        Ok(id) if id != 0 => id,
        _ => match crate::registry::id_of_name(&name).await {
            Ok(id) if id != 0 => id,
            _ => return,
        },
    };
    let published = crate::registry::push_sub_of(token_id).await.ok().flatten();
    // MULTI-DEVICE merge: only write when THIS device's entry is missing or
    // stale in the slot array (None = already current, no tx).
    let Some(merged) = crate::registry::merge_push_sub(published.as_deref(), &current) else {
        return;
    };
    let publish = async {
        let registry_addr = crate::encoding::parse_address(crate::registry::REGISTRY_ADDRESS)?;
        let call = crate::tempo_tx::TempoCall {
            to: registry_addr,
            value_wei: 0,
            input: crate::registry::encode_set_push_sub(token_id, merged.as_bytes()),
        };
        let gas = crate::app::gas::set_metadata_gas(merged.len());
        crate::app::events::run_sponsored_tempo_call(
            &owner,
            vec![call],
            gas,
            "refresh push subscription",
        )
        .await
    };
    match publish.await {
        Err(e) => web_sys::console::warn_1(&wasm_bindgen::JsValue::from_str(&format!(
            "push subscription refresh failed: {e}"
        ))),
        Ok(_) => web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(
            "stale push subscription refreshed on-chain",
        )),
    }
}

/// HEADLESS auto-registration: on every app load, if notification permission is
/// ALREADY granted AND this device already has an identity, (re)publish its
/// ADDRESS-KEYED Web Push subscription — no gesture, no prompt, works for any
/// visitor (no MAIN needed). After the ONE-TIME permission grant (via the bell),
/// this keeps the device registered so a READY-UP broadcast always reaches it.
/// Idempotent: skips the sponsored write when the on-chain sub already matches.
pub(crate) async fn auto_register_device_push() {
    if !matches!(
        web_sys::Notification::permission(),
        web_sys::NotificationPermission::Granted
    ) {
        return; // no permission yet — the one-time bell tap must grant it first
    }
    // Only if an identity ALREADY exists — never silently mint a wallet on load.
    if crate::app::chat::credit_address_existing().await.is_none() {
        return;
    }
    let Some((signer, addr)) = crate::app::chat::credit_signer().await else {
        return;
    };
    let Ok(current) = subscribe_push().await else {
        return;
    };
    let addr_hex = crate::encoding::bytes_to_hex_str(&addr);
    let slot = crate::registry::addr_push_sub_of(&addr_hex).await.ok().flatten();
    // MULTI-DEVICE merge: None = this device is already in the slot array.
    let Some(merged) = crate::registry::merge_push_sub(slot.as_deref(), &current) else {
        return; // already up to date
    };
    let Ok(sponsor) = crate::app::sponsor::signer() else {
        return;
    };
    let token = crate::registry::ALPHA_USD_ADDRESS;
    match crate::registry::set_push_sub_sponsored(&signer, &sponsor, merged.as_bytes(), token).await
    {
        Ok(_) => web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(
            "[push] device auto-registered (address-keyed)",
        )),
        Err(e) => web_sys::console::warn_1(&wasm_bindgen::JsValue::from_str(&format!(
            "[push] auto-register failed: {e}"
        ))),
    }
}