Skip to main content

euv_example/pages/dynamic/
fn.rs

1use super::*;
2
3/// Runs the real local HTTP `.wasm` download flow on native targets or the sandboxed browser flow on `wasm32`.
4///
5/// # Arguments
6///
7/// - `&WasmDynamicManager` - Active dynamic WASM manager.
8/// - `Signal<String>` - Live status readout signal.
9pub(crate) fn run_dynamic_http_wasm(mgr: &WasmDynamicManager, status_sig: Signal<String>) {
10    #[cfg(not(target_arch = "wasm32"))]
11    {
12        let bytes: Vec<u8> = build_partial_widget_wasm(DYNAMIC_HTTP_MODULE_TITLE, 3, 0x059669);
13        let bytes_srv: Vec<u8> = bytes.clone();
14        match TcpListener::bind(DYNAMIC_HTTP_BIND_ADDR) {
15            Ok(listener) => {
16                let port: u16 = listener
17                    .local_addr()
18                    .map(|addr: SocketAddr| addr.port())
19                    .unwrap_or(0);
20                drop(spawn(move || {
21                    if let Ok((mut stream, _)) = listener.accept() {
22                        let mut req_buf: [u8; 512] = [0; 512];
23                        let _: Result<usize, Error> = stream.read(&mut req_buf);
24                        let hdr: String = format!(
25                            "HTTP/1.1 200 OK\r\nContent-Type: application/wasm\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
26                            bytes_srv.len()
27                        );
28                        let _: Result<(), Error> = stream.write_all(hdr.as_bytes());
29                        let _: Result<(), Error> = stream.write_all(&bytes_srv);
30                        let _: Result<(), Error> = stream.flush();
31                    }
32                }));
33                let url: String = format!("http://127.0.0.1:{port}/live-module-v3.wasm");
34                let req: WasmDownloadRequest =
35                    WasmDownloadRequest::partial(url.clone(), SLOT_WASM_WIDGET.to_string(), 3)
36                        .with_checksum(compute_wasm_checksum(&bytes))
37                        .with_signature(compute_wasm_signature(
38                            &bytes,
39                            3,
40                            WASM_SHOWCASE_SIGNING_KEY,
41                        ))
42                        .with_allow_downgrade(true);
43                match mgr.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
44                    Ok(item_val) => {
45                        let _: bool = status_sig.set(format!(
46                            "Downloaded {} bytes over real HTTP ({url}) -> executed & mounted .wasm v{item_val} natively!",
47                            bytes.len()
48                        ));
49                    }
50                    Err(event_ref) => {
51                        let _: bool =
52                            status_sig.set(format!("HTTP .wasm download failed: {event_ref}"));
53                    }
54                }
55            }
56            Err(err) => {
57                let _: bool = status_sig.set(format!("Local HTTP server bind error: {err}"));
58            }
59        }
60    }
61    #[cfg(target_arch = "wasm32")]
62    {
63        let bytes: Vec<u8> = build_partial_widget_wasm(TITLE_WASM_PARTIAL_V1, 1, 0x2563EB);
64        let req: WasmDownloadRequest = WasmDownloadRequest::partial(
65            URL_WASM_PARTIAL_V1.to_string(),
66            SLOT_WASM_WIDGET.to_string(),
67            1,
68        )
69        .with_checksum(compute_wasm_checksum(&bytes))
70        .with_signature(compute_wasm_signature(&bytes, 1, WASM_SHOWCASE_SIGNING_KEY))
71        .with_allow_downgrade(true);
72        match mgr.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
73            Ok(tex_v) => {
74                let _: bool = status_sig.set(format!(
75                    "Fetched & executed .wasm v{tex_v} natively in browser sandbox"
76                ));
77            }
78            Err(error_val) => {
79                let _: bool = status_sig.set(format!("WASM fetch failed: {error_val}"));
80            }
81        }
82    }
83}
84
85/// Mounts the native hot-swapped banner v2 widget returned by `DynamicUpdateHub::swap_component_builder`.
86///
87/// # Arguments
88///
89/// - `u64` - Target banner revision number.
90/// - `DynamicUpdateHub` - Hub receiving offer claim actions.
91/// - `ThemeTokens` - Active design tokens.
92///
93/// # Returns
94///
95/// - `NodeId` - Mounted native banner node.
96pub(crate) fn mount_dynamic_native_banner(
97    next_v: u64,
98    hub_click: DynamicUpdateHub,
99    tokens: ThemeTokens,
100) -> NodeId {
101    let banner_title: String = format!("Native Hot-Swapped Banner v{next_v} (Zero Restart)");
102    let on_claim = move |_: &UiEvent| {
103        hub_click.dispatch_action(DynamicActionEvent::new(
104            SLOT_PROMO_BANNER.to_string(),
105            DYNAMIC_ACTION_CLAIM_OFFER.to_string(),
106            format!("native-v{next_v}"),
107        ));
108    };
109    let row_quaternary_style: Style = style! {
110        Width(Length::Percent(100.0))
111        FlexWrap::Wrap
112        Padding(Edges::all(SPACE_MD))
113        Gap(SPACE_MD)
114        AlignItems::Center
115        Background(Color::hex(0x064E3B))
116        Radius(8.0)
117        Overflow::Hidden
118    };
119    let text_twelfth_style: Style = style! {
120        FlexGrow(1.0)
121        FlexShrink(1.0)
122        MinWidth(Length::Px(0.0))
123        FontSize(14.0)
124        FontWeight::Bold
125        TextColor(Color::hex(0xECFDF5))
126    };
127    view! {
128        row {
129            style: row_quaternary_style
130            text {
131                style: text_twelfth_style
132                { banner_title }
133            }
134            EuvButton {
135                label: BTN_CLAIM_OFFER.to_string()
136                tokens: tokens
137                on_click: on_claim
138            }
139        }
140    }
141}
142
143/// Mounts the Scoped / Partial Dynamic WASM Execution card.
144///
145/// # Arguments
146///
147/// - `&ShowcaseState` - Shared showcase state.
148/// - `ThemeTokens` - Active design tokens.
149///
150/// # Returns
151///
152/// - `NodeId` - Mounted partial WASM card node.
153pub(crate) fn mount_dynamic_partial_wasm_card(
154    state: &ShowcaseState,
155    tokens: ThemeTokens,
156) -> NodeId {
157    let palette: ThemePalette = tokens.get_palette();
158    let geometry: ThemeGeometry = tokens.get_geometry();
159    let wasm_mgr: WasmDynamicManager = state.get_wasm_manager().clone();
160    let wasm_reg: RegistryWasmFetcher = state.get_wasm_registry().clone();
161    let wasm_offline_sig: Signal<bool> = state.get_wasm_offline();
162    let wasm_status_sig: Signal<String> = state.get_wasm_fault_status();
163    let partial_scope: WasmDynamicScope = WasmDynamicScope::Partial {
164        slot_id: SLOT_WASM_WIDGET.to_string(),
165    };
166    let partial_state_sig: Signal<WasmLoadState> = wasm_mgr.state_signal(&partial_scope);
167    let global_state_sig: Signal<WasmLoadState> = wasm_mgr.state_signal(&WasmDynamicScope::Global);
168    let wasm_tel_sig: Signal<WasmDynamicTelemetry> = wasm_mgr.telemetry();
169    let m_http: WasmDynamicManager = wasm_mgr.clone();
170    let m_p1: WasmDynamicManager = wasm_mgr.clone();
171    let m_p2: WasmDynamicManager = wasm_mgr.clone();
172    let m_prb: WasmDynamicManager = wasm_mgr.clone();
173    let m_pun: WasmDynamicManager = wasm_mgr;
174    let on_http = move |_: &UiEvent| {
175        run_dynamic_http_wasm(&m_http, wasm_status_sig);
176    };
177    let on_p1 = move |_: &UiEvent| {
178        let bytes: Vec<u8> = build_partial_widget_wasm(TITLE_WASM_PARTIAL_V1, 1, 0x2563EB);
179        let req: WasmDownloadRequest = WasmDownloadRequest::partial(
180            URL_WASM_PARTIAL_V1.to_string(),
181            SLOT_WASM_WIDGET.to_string(),
182            1,
183        )
184        .with_checksum(compute_wasm_checksum(&bytes))
185        .with_signature(compute_wasm_signature(&bytes, 1, WASM_SHOWCASE_SIGNING_KEY))
186        .with_allow_downgrade(true);
187        match m_p1.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
188            Ok(item_val) => {
189                let _: bool = wasm_status_sig.set(format!(
190                    "Mounted Partial .wasm v{item_val} natively (verified checksum + signature)"
191                ));
192            }
193            Err(event_ref) => {
194                let _: bool = wasm_status_sig.set(format!("Partial v1 failed: {event_ref}"));
195            }
196        }
197    };
198    let on_p2 = move |_: &UiEvent| {
199        let bytes: Vec<u8> = build_partial_widget_wasm(DYNAMIC_PARTIAL_V2_TITLE, 2, 0x7C3AED);
200        let req: WasmDownloadRequest = WasmDownloadRequest::partial(
201            URL_WASM_PARTIAL_V2.to_string(),
202            SLOT_WASM_WIDGET.to_string(),
203            2,
204        )
205        .with_checksum(compute_wasm_checksum(&bytes))
206        .with_signature(compute_wasm_signature(&bytes, 2, WASM_SHOWCASE_SIGNING_KEY))
207        .with_allow_downgrade(true);
208        match m_p2.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
209            Ok(tex_v) => {
210                let _: bool = wasm_status_sig.set(format!(
211                    "Hot-swapped Partial .wasm v{tex_v} natively (sibling UI untouched)"
212                ));
213            }
214            Err(error_val) => {
215                let _: bool = wasm_status_sig.set(format!("Partial v2 failed: {error_val}"));
216            }
217        }
218    };
219    let on_offline = move |_: &UiEvent| {
220        let next: bool = !wasm_offline_sig.get_untracked();
221        let _: bool = wasm_offline_sig.set(next);
222        wasm_reg.set_offline(next);
223        let msg: &str = if next {
224            DYNAMIC_OFFLINE_ON_MSG
225        } else {
226            DYNAMIC_OFFLINE_OFF_MSG
227        };
228        let _: bool = wasm_status_sig.set(msg.to_string());
229    };
230    let on_rollback_partial = move |_: &UiEvent| match m_prb
231        .rollback_partial(SLOT_WASM_WIDGET, DYNAMIC_ROLLBACK_REASON)
232    {
233        Ok(bary_v) => {
234            let _: bool =
235                wasm_status_sig.set(format!("Rolled back partial WASM slot to v{bary_v}"));
236        }
237        Err(entry_ref) => {
238            let _: bool = wasm_status_sig.set(format!("Rollback: {entry_ref}"));
239        }
240    };
241    let on_unmount = move |_: &UiEvent| {
242        m_pun.unmount_partial(SLOT_WASM_WIDGET);
243        let _: bool = wasm_status_sig.set(DYNAMIC_UNMOUNT_MSG.to_string());
244    };
245    let wasm_tel_text = move || -> String {
246        let node_style: WasmLoadState = partial_state_sig.get();
247        let gst: WasmLoadState = global_state_sig.get();
248        let tel: WasmDynamicTelemetry = wasm_tel_sig.get();
249        format!(
250            "Partial={node_style:?} | Global={gst:?} | OK={}/{} Cache={} Retries={} Rollbacks={} Traps={} FuelStops={} Rejects={} Events={}",
251            tel.get_downloads_succeeded(),
252            tel.get_downloads_started(),
253            tel.get_cache_hits(),
254            tel.get_retries_performed(),
255            tel.get_rollbacks_executed(),
256            tel.get_sandbox_traps_caught(),
257            tel.get_fuel_exhaustions_caught(),
258            tel.get_integrity_rejections(),
259            tel.get_events_handled()
260        )
261    };
262    let column_eighth_style: Style = style! {
263        Width(Length::Percent(100.0))
264        Gap(SPACE_MD)
265    };
266    let row_tertiary_style: Style = style! {
267        Width(Length::Percent(100.0))
268        Padding(Edges::all(SPACE_MD))
269        Background(palette.get_muted())
270        Border::new(geometry.get_border_width(), palette.get_border())
271        Radius(geometry.get_radius_md())
272        Overflow::Hidden
273    };
274    let text_tenth_style: Style = style! {
275        Width(Length::Percent(100.0))
276        FontSize(13.0)
277        TextColor(palette.get_muted_foreground())
278    };
279    let text_eleventh_style: Style = style! {
280        Width(Length::Percent(100.0))
281        FontSize(12.0)
282        FontFamily::Monospace
283        TextColor(palette.get_muted_foreground())
284    };
285    view! {
286        EuvCard {
287            title: DYNAMIC_PARTIAL_CARD_TITLE.to_string()
288            tokens: tokens
289            subtitle: DYNAMIC_PARTIAL_CARD_SUB
290            column {
291                style: column_eighth_style
292                EuvActionRow {
293                    EuvButton {
294                        label: DYNAMIC_BTN_HTTP_WASM.to_string()
295                        tokens: tokens
296                        on_click: on_http
297                    }
298                    EuvButton {
299                        label: DYNAMIC_BTN_PARTIAL_V1.to_string()
300                        tokens: tokens
301                        outline()
302                        on_click: on_p1
303                    }
304                    EuvButton {
305                        label: DYNAMIC_BTN_PARTIAL_V2.to_string()
306                        tokens: tokens
307                        outline()
308                        on_click: on_p2
309                    }
310                    EuvButton {
311                        label: DYNAMIC_BTN_TOGGLE_OFFLINE.to_string()
312                        tokens: tokens
313                        outline()
314                        on_click: on_offline
315                    }
316                    EuvButton {
317                        label: DYNAMIC_BTN_ROLLBACK_PARTIAL.to_string()
318                        tokens: tokens
319                        outline()
320                        on_click: on_rollback_partial
321                    }
322                    EuvButton {
323                        label: DYNAMIC_BTN_UNMOUNT_SLOT.to_string()
324                        tokens: tokens
325                        ghost()
326                        on_click: on_unmount
327                    }
328                }
329                slot {
330                    id: SLOT_WASM_WIDGET
331                    row {
332                        style: row_tertiary_style
333                        text {
334                            style: text_tenth_style
335                            { DYNAMIC_SLOT_WASM_FALLBACK }
336                        }
337                    }
338                }
339                text {
340                    style: text_eleventh_style
341                    { wasm_tel_text }
342                }
343            }
344        }
345    }
346}
347
348/// Mounts the Global / Full-App Dynamic WASM Takeover card.
349///
350/// # Arguments
351///
352/// - `&ShowcaseState` - Shared showcase state.
353/// - `ThemeTokens` - Active design tokens.
354///
355/// # Returns
356///
357/// - `NodeId` - Mounted global WASM takeover card node.
358pub(crate) fn mount_dynamic_global_wasm_card(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
359    let palette: ThemePalette = tokens.get_palette();
360    let wasm_mgr: WasmDynamicManager = state.get_wasm_manager().clone();
361    let wasm_status_sig: Signal<String> = state.get_wasm_fault_status();
362    let m_g1: WasmDynamicManager = wasm_mgr.clone();
363    let m_g2: WasmDynamicManager = wasm_mgr.clone();
364    let m_gbad: WasmDynamicManager = wasm_mgr.clone();
365    let m_grb: WasmDynamicManager = wasm_mgr;
366    let on_g1 = move |_: &UiEvent| {
367        let bytes: Vec<u8> = build_global_app_wasm(DYNAMIC_GLOBAL_V1_TITLE, 1);
368        let req: WasmDownloadRequest =
369            WasmDownloadRequest::global(URL_WASM_GLOBAL_V1.to_string(), 1)
370                .with_checksum(compute_wasm_checksum(&bytes))
371                .with_signature(compute_wasm_signature(&bytes, 1, WASM_SHOWCASE_SIGNING_KEY))
372                .with_allow_downgrade(true);
373        match m_g1.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
374            Ok(item_val) => {
375                let _: bool = wasm_status_sig.set(format!(
376                    "Global .wasm v{item_val} took over root shell natively!"
377                ));
378            }
379            Err(event_ref) => {
380                let _: bool = wasm_status_sig.set(format!("Global v1 failed: {event_ref}"));
381            }
382        }
383    };
384    let on_g2 = move |_: &UiEvent| {
385        let bytes: Vec<u8> = build_global_app_wasm(DYNAMIC_GLOBAL_V2_TITLE, 2);
386        let req: WasmDownloadRequest =
387            WasmDownloadRequest::global(URL_WASM_GLOBAL_V2.to_string(), 2)
388                .with_checksum(compute_wasm_checksum(&bytes))
389                .with_signature(compute_wasm_signature(&bytes, 2, WASM_SHOWCASE_SIGNING_KEY))
390                .with_allow_downgrade(true);
391        match m_g2.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
392            Ok(tex_v) => {
393                let _: bool =
394                    wasm_status_sig.set(format!("Upgraded Global .wasm to v{tex_v} atomically"));
395            }
396            Err(error_val) => {
397                let _: bool = wasm_status_sig.set(format!("Global v2 failed: {error_val}"));
398            }
399        }
400    };
401    let on_gbad = move |_: &UiEvent| {
402        let req: WasmDownloadRequest = WasmDownloadRequest::global(URL_WASM_TRAP.to_string(), 99);
403        match m_gbad.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
404            Ok(bary_v) => {
405                let _: bool = wasm_status_sig.set(format!("Unexpected global mount v{bary_v}"));
406            }
407            Err(entry_ref) => {
408                let _: bool = wasm_status_sig.set(format!(
409                    "Global fault isolated & LKG preserved: {entry_ref}"
410                ));
411            }
412        }
413    };
414    let on_restore = move |_: &UiEvent| {
415        m_grb.restore_native_global();
416        let _: bool = wasm_status_sig.set(STATUS_RESTORED_NATIVE_SHELL.to_string());
417    };
418    let status_text = move || -> String { wasm_status_sig.get() };
419    let column_seventh_style: Style = style! {
420        Width(Length::Percent(100.0))
421        Gap(SPACE_MD)
422    };
423    let text_ninth_style: Style = style! {
424        Width(Length::Percent(100.0))
425        FontSize(12.5)
426        FontWeight::Medium
427        TextColor(palette.get_primary())
428    };
429    view! {
430        EuvCard {
431            title: DYNAMIC_GLOBAL_CARD_TITLE.to_string()
432            tokens: tokens
433            subtitle: DYNAMIC_GLOBAL_CARD_SUB
434            column {
435                style: column_seventh_style
436                EuvActionRow {
437                    EuvButton {
438                        label: DYNAMIC_BTN_GLOBAL_V1.to_string()
439                        tokens: tokens
440                        on_click: on_g1
441                    }
442                    EuvButton {
443                        label: DYNAMIC_BTN_GLOBAL_V2.to_string()
444                        tokens: tokens
445                        outline()
446                        on_click: on_g2
447                    }
448                    EuvButton {
449                        label: DYNAMIC_BTN_GLOBAL_FAULT.to_string()
450                        tokens: tokens
451                        destructive()
452                        on_click: on_gbad
453                    }
454                    EuvButton {
455                        label: DYNAMIC_BTN_RESTORE_NATIVE.to_string()
456                        tokens: tokens
457                        outline()
458                        on_click: on_restore
459                    }
460                }
461                text {
462                    style: text_ninth_style
463                    { status_text }
464                }
465            }
466        }
467    }
468}
469
470/// Mounts the Security, Fault & Sandbox Verification Matrix card.
471///
472/// # Arguments
473///
474/// - `&ShowcaseState` - Shared showcase state.
475/// - `ThemeTokens` - Active design tokens.
476///
477/// # Returns
478///
479/// - `NodeId` - Mounted fault matrix card node.
480pub(crate) fn mount_dynamic_fault_card(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
481    let palette: ThemePalette = tokens.get_palette();
482    let wasm_mgr: WasmDynamicManager = state.get_wasm_manager().clone();
483    let wasm_status_sig: Signal<String> = state.get_wasm_fault_status();
484    let m_retry: WasmDynamicManager = wasm_mgr.clone();
485    let on_retry = move |_: &UiEvent| {
486        let req: WasmDownloadRequest = WasmDownloadRequest::partial(
487            URL_WASM_TIMEOUT_RETRY.to_string(),
488            SLOT_WASM_WIDGET.to_string(),
489            10,
490        )
491        .with_allow_downgrade(true);
492        match m_retry.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY) {
493            Ok(item_val) => {
494                let _: bool = wasm_status_sig.set(format!(
495                    "PASS Timeout->Retry recovered and mounted v{item_val}!"
496                ));
497            }
498            Err(event_ref) => {
499                let _: bool = wasm_status_sig.set(format!("Retry failed: {event_ref}"));
500            }
501        }
502    };
503    let m_tamper: WasmDynamicManager = wasm_mgr.clone();
504    let on_tamper = move |_: &UiEvent| {
505        let good: Vec<u8> = build_partial_widget_wasm(TITLE_WASM_PARTIAL_V1, 1, 0x2563EB);
506        let req: WasmDownloadRequest = WasmDownloadRequest::partial(
507            URL_WASM_TAMPERED.to_string(),
508            SLOT_WASM_WIDGET.to_string(),
509            13,
510        )
511        .with_checksum(compute_wasm_checksum(&good))
512        .with_allow_downgrade(true);
513        let res: String = format!(
514            "Blocked Tampered Checksum -> {:?}",
515            m_tamper.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY)
516        );
517        let _: bool = wasm_status_sig.set(res);
518    };
519    let m_sig: WasmDynamicManager = wasm_mgr.clone();
520    let on_sig = move |_: &UiEvent| {
521        let req: WasmDownloadRequest = WasmDownloadRequest::partial(
522            URL_WASM_PARTIAL_V1.to_string(),
523            SLOT_WASM_WIDGET.to_string(),
524            14,
525        )
526        .with_signature(DYNAMIC_FORGED_SIG.to_string())
527        .with_allow_downgrade(true);
528        let res: String = format!(
529            "Blocked Forged Signature -> {:?}",
530            m_sig.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY)
531        );
532        let _: bool = wasm_status_sig.set(res);
533    };
534    let m_cancel: WasmDynamicManager = wasm_mgr.clone();
535    let on_cancel = move |_: &UiEvent| {
536        let gen_id: u64 = m_cancel.cancel_scope(&WasmDynamicScope::Partial {
537            slot_id: SLOT_WASM_WIDGET.to_string(),
538        });
539        let _: bool = wasm_status_sig.set(format!(
540            "Cancelled scope request cleanly (generation #{gen_id} blocks stale responses)"
541        ));
542    };
543    let standard_faults: [(&str, &str, u64, &str); 7] = [
544        (
545            DYNAMIC_BTN_FAULT_500,
546            URL_WASM_HTTP_500,
547            11,
548            DYNAMIC_FAULT_MSG_500,
549        ),
550        (
551            DYNAMIC_BTN_FAULT_CORRUPT,
552            URL_WASM_CORRUPTED,
553            12,
554            DYNAMIC_FAULT_MSG_CORRUPT,
555        ),
556        (
557            DYNAMIC_BTN_FAULT_ABI,
558            URL_WASM_BAD_ABI,
559            15,
560            DYNAMIC_FAULT_MSG_ABI,
561        ),
562        (
563            DYNAMIC_BTN_FAULT_EXPORT,
564            URL_WASM_MISSING_EXPORT,
565            16,
566            DYNAMIC_FAULT_MSG_EXPORT,
567        ),
568        (
569            DYNAMIC_BTN_FAULT_FUEL,
570            URL_WASM_FUEL_BOMB,
571            17,
572            DYNAMIC_FAULT_MSG_FUEL,
573        ),
574        (
575            DYNAMIC_BTN_FAULT_TRAP,
576            URL_WASM_TRAP,
577            18,
578            DYNAMIC_FAULT_MSG_TRAP,
579        ),
580        (
581            DYNAMIC_BTN_FAULT_BIG,
582            URL_WASM_OVERSIZED,
583            19,
584            DYNAMIC_FAULT_MSG_BIG,
585        ),
586    ];
587    let standard_btns: Vec<NodeId> = standard_faults
588        .into_iter()
589        .map(|(label, url, ver, prefix): (&str, &str, u64, &str)| {
590            let mgr_c: WasmDynamicManager = wasm_mgr.clone();
591            let on_fault = move |_: &UiEvent| {
592                let req: WasmDownloadRequest = WasmDownloadRequest::partial(
593                    url.to_string(),
594                    SLOT_WASM_WIDGET.to_string(),
595                    ver,
596                )
597                .with_allow_downgrade(true);
598                let res: String = format!(
599                    "{prefix} -> {:?}",
600                    mgr_c.load_and_mount(req, WASM_SHOWCASE_SIGNING_KEY)
601                );
602                let _: bool = wasm_status_sig.set(res);
603            };
604            view! {
605                EuvButton {
606                    label: label.to_string()
607                    tokens: tokens
608                    outline()
609                    small()
610                    on_click: on_fault
611                }
612            }
613        })
614        .collect();
615    let status_text = move || -> String { wasm_status_sig.get() };
616    let column_sixth_style: Style = style! {
617        Width(Length::Percent(100.0))
618        Gap(SPACE_MD)
619    };
620    let text_eighth_style: Style = style! {
621        Width(Length::Percent(100.0))
622        FontSize(12.5)
623        FontWeight::Medium
624        TextColor(palette.get_primary())
625    };
626    view! {
627        EuvCard {
628            title: DYNAMIC_FAULT_CARD_TITLE.to_string()
629            tokens: tokens
630            subtitle: DYNAMIC_FAULT_CARD_SUB
631            column {
632                style: column_sixth_style
633                EuvActionRow {
634                    EuvButton {
635                        label: DYNAMIC_BTN_FAULT_RETRY.to_string()
636                        tokens: tokens
637                        outline()
638                        small()
639                        on_click: on_retry
640                    }
641                    EuvButton {
642                        label: DYNAMIC_BTN_FAULT_TAMPER.to_string()
643                        tokens: tokens
644                        outline()
645                        small()
646                        on_click: on_tamper
647                    }
648                    EuvButton {
649                        label: DYNAMIC_BTN_FAULT_SIG.to_string()
650                        tokens: tokens
651                        outline()
652                        small()
653                        on_click: on_sig
654                    }
655                    ..standard_btns
656                    EuvButton {
657                        label: DYNAMIC_BTN_FAULT_CANCEL.to_string()
658                        tokens: tokens
659                        outline()
660                        small()
661                        on_click: on_cancel
662                    }
663                }
664                text {
665                    style: text_eighth_style
666                    { status_text }
667                }
668            }
669        }
670    }
671}
672
673/// Mounts the Component-Level Dynamic Slots card preserving sibling counter state across hot swaps.
674///
675/// # Arguments
676///
677/// - `&ShowcaseState` - Shared showcase state.
678/// - `ThemeTokens` - Active design tokens.
679///
680/// # Returns
681///
682/// - `NodeId` - Mounted component slots card node.
683pub(crate) fn mount_dynamic_component_card(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
684    let palette: ThemePalette = tokens.get_palette();
685    let geometry: ThemeGeometry = tokens.get_geometry();
686    let hub: DynamicUpdateHub = state.get_dynamic_hub().clone();
687    let sibling_counter: Signal<i32> = state.get_sibling_counter();
688    let hub_v1: DynamicUpdateHub = hub.clone();
689    let hub_v2: DynamicUpdateHub = hub.clone();
690    let hub_rb: DynamicUpdateHub = hub.clone();
691    let hub_m1: DynamicUpdateHub = hub.clone();
692    let hub_mrb: DynamicUpdateHub = hub;
693    let sibling_text = move || -> String {
694        let count: i32 = sibling_counter.get();
695        format!("Sibling State Preserved: count={count}")
696    };
697    let on_inc_sibling = move |_: &UiEvent| {
698        let _: bool = sibling_counter.set(sibling_counter.get_untracked() + 1);
699    };
700    let on_push_banner_v1 = move |_: &UiEvent| {
701        let next_v: u64 = hub_v1
702            .component_version(SLOT_PROMO_BANNER)
703            .saturating_add(1);
704        let mut badge: DynamicNodeSpec = DynamicNodeSpec::badge(format!("OTA v{next_v}"));
705        badge
706            .get_mut_style()
707            .set_background_hex(Some(0x1D4ED8))
708            .set_color_hex(Some(0xFFFFFF));
709        let mut title: DynamicNodeSpec = DynamicNodeSpec::text(format!(
710            "Dynamic JSON Banner v{next_v}: Surgical Component Patch"
711        ));
712        title
713            .get_mut_style()
714            .set_bold(true)
715            .set_color_hex(Some(0x1E3A8A));
716        let mut offer_btn: DynamicNodeSpec = DynamicNodeSpec::button(
717            BTN_CLAIM_OFFER.to_string(),
718            DYNAMIC_ACTION_CLAIM_OFFER.to_string(),
719        );
720        offer_btn.set_payload(format!("json-v{next_v}"));
721        let mut box_spec: DynamicNodeSpec = DynamicNodeSpec::row()
722            .child(badge)
723            .child(title)
724            .child(offer_btn);
725        box_spec
726            .get_mut_style()
727            .set_full_width(true)
728            .set_padding(Some(SPACE_MD))
729            .set_radius(Some(SPACE_SM))
730            .set_background_hex(Some(0xEFF6FF))
731            .set_border_width(Some(1.0))
732            .set_border_hex(Some(0x93C5FD));
733        let mut upd: DynamicComponentUpdate =
734            DynamicComponentUpdate::new(SLOT_PROMO_BANNER.to_string(), next_v, box_spec);
735        upd.sign();
736        if let Ok(json) = upd.to_json() {
737            let _: Result<u64, DynamicUpdateError> = hub_v1.apply_component_json(&json);
738        }
739    };
740    let on_push_banner_v2 = move |_: &UiEvent| {
741        let next_v: u64 = hub_v2
742            .component_version(SLOT_PROMO_BANNER)
743            .saturating_add(1)
744            .max(2);
745        let hub_act: DynamicUpdateHub = hub_v2.clone();
746        let _: Result<u64, DynamicUpdateError> =
747            hub_v2.swap_component_builder(SLOT_PROMO_BANNER.to_string(), next_v, move || {
748                mount_dynamic_native_banner(next_v, hub_act.clone(), tokens)
749            });
750    };
751    let on_rollback_banner = move |_: &UiEvent| {
752        let _: Result<u64, DynamicUpdateError> = hub_rb.rollback_component(SLOT_PROMO_BANNER);
753    };
754    let on_patch_metrics = move |_: &UiEvent| {
755        let next_v: u64 = hub_m1
756            .component_version(SLOT_METRICS_WIDGET)
757            .saturating_add(1);
758        let mut card_spec: DynamicNodeSpec = DynamicNodeSpec::card(format!(
759            "Live Metrics Widget v{next_v}"
760        ))
761        .child(DynamicNodeSpec::text(format!(
762            "Updated independently without touching promo_banner or sibling state (rev {next_v})."
763        )));
764        card_spec
765            .get_mut_style()
766            .set_background_hex(Some(0xFEFCE8))
767            .set_border_width(Some(1.0))
768            .set_border_hex(Some(0xFACC15));
769        let mut upd: DynamicComponentUpdate =
770            DynamicComponentUpdate::new(SLOT_METRICS_WIDGET.to_string(), next_v, card_spec);
771        upd.sign();
772        let _: Result<u64, DynamicUpdateError> = hub_m1.apply_component(upd);
773    };
774    let on_rollback_metrics = move |_: &UiEvent| {
775        let _: Result<u64, DynamicUpdateError> = hub_mrb.rollback_component(SLOT_METRICS_WIDGET);
776    };
777    let column_fifth_style: Style = style! {
778        Width(Length::Percent(100.0))
779        Gap(SPACE_MD)
780    };
781    let text_fifth_style: Style = style! {
782        Width(Length::Percent(100.0))
783        FontSize(13.0)
784        FontWeight::SemiBold
785        TextColor(palette.get_primary())
786    };
787    let row_secondary_style: Style = style! {
788        Width(Length::Percent(100.0))
789        Padding(Edges::all(SPACE_MD))
790        Background(palette.get_muted())
791        Border::new(geometry.get_border_width(), palette.get_border())
792        Radius(geometry.get_radius_md())
793        Overflow::Hidden
794    };
795    let text_sixth_style: Style = style! {
796        Width(Length::Percent(100.0))
797        FontSize(13.0)
798        TextColor(palette.get_foreground())
799    };
800    let text_seventh_style: Style = style! {
801        Width(Length::Percent(100.0))
802        FontSize(13.0)
803        TextColor(palette.get_muted_foreground())
804    };
805    view! {
806        EuvCard {
807            title: DYNAMIC_COMP_CARD_TITLE.to_string()
808            tokens: tokens
809            subtitle: DYNAMIC_COMP_CARD_SUB
810            column {
811                style: column_fifth_style
812                EuvActionRow {
813                    EuvButton {
814                        label: BTN_INC_SIBLING.to_string()
815                        tokens: tokens
816                        outline()
817                        on_click: on_inc_sibling
818                    }
819                }
820                text {
821                    style: text_fifth_style
822                    { sibling_text }
823                }
824                EuvActionRow {
825                    EuvButton {
826                        label: BTN_PUSH_BANNER_V1.to_string()
827                        tokens: tokens
828                        on_click: on_push_banner_v1
829                    }
830                    EuvButton {
831                        label: BTN_PUSH_BANNER_V2.to_string()
832                        tokens: tokens
833                        outline()
834                        on_click: on_push_banner_v2
835                    }
836                    EuvButton {
837                        label: BTN_ROLLBACK_BANNER.to_string()
838                        tokens: tokens
839                        outline()
840                        on_click: on_rollback_banner
841                    }
842                }
843                slot {
844                    id: SLOT_PROMO_BANNER
845                    row {
846                        style: row_secondary_style
847                        text {
848                            style: text_sixth_style
849                            { DYNAMIC_SLOT_BANNER_FALLBACK }
850                        }
851                    }
852                }
853                EuvActionRow {
854                    EuvButton {
855                        label: BTN_PATCH_METRICS.to_string()
856                        tokens: tokens
857                        on_click: on_patch_metrics
858                    }
859                    EuvButton {
860                        label: BTN_ROLLBACK_METRICS.to_string()
861                        tokens: tokens
862                        outline()
863                        on_click: on_rollback_metrics
864                    }
865                }
866                slot {
867                    id: SLOT_METRICS_WIDGET
868                    row {
869                        style: row_secondary_style
870                        text {
871                            style: text_seventh_style
872                            { DYNAMIC_SLOT_METRICS_FALLBACK }
873                        }
874                    }
875                }
876            }
877        }
878    }
879}
880
881/// Mounts the Page-Level Dynamic Updates & Runtime Route Injection card.
882///
883/// # Arguments
884///
885/// - `&ShowcaseState` - Shared showcase state.
886/// - `ThemeTokens` - Active design tokens.
887///
888/// # Returns
889///
890/// - `NodeId` - Mounted page-level dynamic updates card node.
891pub(crate) fn mount_dynamic_page_slot_card(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
892    let palette: ThemePalette = tokens.get_palette();
893    let geometry: ThemeGeometry = tokens.get_geometry();
894    let hub: DynamicUpdateHub = state.get_dynamic_hub().clone();
895    let action_log: Signal<String> = state.get_dynamic_action_log();
896    let route_sig: Signal<String> = state.get_route();
897    let tel_sig: Signal<DynamicTelemetry> = hub.telemetry();
898    let banner_rev: Signal<u64> = hub.component_revision_signal(SLOT_PROMO_BANNER);
899    let metrics_rev: Signal<u64> = hub.component_revision_signal(SLOT_METRICS_WIDGET);
900    let panel_rev: Signal<u64> = hub.page_revision_signal(ROUTE_DYNAMIC_PANEL);
901    let hub_p1: DynamicUpdateHub = hub.clone();
902    let hub_bundle: DynamicUpdateHub = hub.clone();
903    let hub_prb: DynamicUpdateHub = hub.clone();
904    let hub_inject: DynamicUpdateHub = hub.clone();
905    let hub_for_status: DynamicUpdateHub = hub;
906    let on_update_page = move |_: &UiEvent| {
907        let next_v: u64 = hub_p1.page_version(ROUTE_DYNAMIC_PANEL).saturating_add(1);
908        let spec: DynamicNodeSpec =
909            DynamicNodeSpec::card(format!("Hot-Updated Dynamic Page Panel v{next_v}"))
910                .child(DynamicNodeSpec::badge(format!("Page Revision v{next_v}")))
911                .child(DynamicNodeSpec::text(
912                    DYNAMIC_PAGE_REPLACED_BODY.to_string(),
913                ));
914        let mut upd: DynamicPageUpdate = DynamicPageUpdate::new(
915            ROUTE_DYNAMIC_PANEL.to_string(),
916            format!("Dynamic Panel v{next_v}"),
917            next_v,
918            spec,
919        );
920        upd.sign();
921        let _: Result<u64, DynamicUpdateError> = hub_p1.apply_page(upd);
922    };
923    let on_apply_bundle = move |_: &UiEvent| {
924        let next_comp_v: u64 = hub_bundle
925            .component_version(SLOT_METRICS_WIDGET)
926            .saturating_add(1);
927        let next_page_v: u64 = hub_bundle
928            .page_version(ROUTE_DYNAMIC_PANEL)
929            .saturating_add(1);
930        let mut comp_upd: DynamicComponentUpdate = DynamicComponentUpdate::new(
931            SLOT_METRICS_WIDGET.to_string(),
932            next_comp_v,
933            DynamicNodeSpec::card(format!("Atomic Bundle Metrics v{next_comp_v}")).child(
934                DynamicNodeSpec::text(DYNAMIC_ATOMIC_METRICS_BODY.to_string()),
935            ),
936        );
937        comp_upd.sign();
938        let mut page_upd: DynamicPageUpdate = DynamicPageUpdate::new(
939            ROUTE_DYNAMIC_PANEL.to_string(),
940            format!("Atomic Panel v{next_page_v}"),
941            next_page_v,
942            DynamicNodeSpec::card(format!("Atomic Bundle Page Panel v{next_page_v}"))
943                .child(DynamicNodeSpec::text(DYNAMIC_ATOMIC_PAGE_BODY.to_string())),
944        );
945        page_upd.sign();
946        let bundle: DynamicUpdateBundle =
947            DynamicUpdateBundle::new(DYNAMIC_ATOMIC_BUNDLE_ID.to_string(), next_page_v)
948                .push_component(comp_upd)
949                .push_page(page_upd);
950        if let Ok(json) = bundle.to_json() {
951            let _: Result<DynamicTelemetry, DynamicUpdateError> =
952                hub_bundle.apply_bundle_json(&json);
953        }
954    };
955    let on_rollback_page = move |_: &UiEvent| {
956        let _: Result<u64, DynamicUpdateError> = hub_prb.rollback_page(ROUTE_DYNAMIC_PANEL);
957    };
958    let on_inject_route = move |_: &UiEvent| {
959        let next_v: u64 = hub_inject.page_version(ROUTE_PROMO_LIVE).saturating_add(1);
960        let mut back_btn: DynamicNodeSpec = DynamicNodeSpec::button(
961            BTN_RETURN_DYNAMIC.to_string(),
962            DYNAMIC_ACTION_RETURN.to_string(),
963        );
964        back_btn.set_payload(format!("from-promo-v{next_v}"));
965        let page_spec: DynamicNodeSpec = DynamicNodeSpec::column().child(
966            DynamicNodeSpec::card(format!("Runtime-Injected Page /promo-live (v{next_v})"))
967                .child(DynamicNodeSpec::badge(DYNAMIC_PROMO_BADGE.to_string()))
968                .child(DynamicNodeSpec::text(DYNAMIC_PROMO_BODY.to_string()))
969                .child(back_btn),
970        );
971        let mut upd: DynamicPageUpdate = DynamicPageUpdate::new(
972            ROUTE_PROMO_LIVE.to_string(),
973            DYNAMIC_PROMO_TITLE.to_string(),
974            next_v,
975            page_spec,
976        );
977        upd.sign();
978        if let Ok(json) = upd.to_json()
979            && hub_inject.apply_page_json(&json).is_ok()
980        {
981            let _: bool = route_sig.set_if_changed(ROUTE_PROMO_LIVE.to_string());
982        }
983    };
984    let versions_text = move || -> String {
985        let _: u64 = banner_rev.get();
986        let _: u64 = metrics_rev.get();
987        let _: u64 = panel_rev.get();
988        let tel: DynamicTelemetry = tel_sig.get();
989        format!(
990            "Versions: banner=v{} metrics=v{} panel=v{} | Applied: comp={} page={} rollbacks={} rejected={} | Last Action: {}",
991            hub_for_status.component_version(SLOT_PROMO_BANNER),
992            hub_for_status.component_version(SLOT_METRICS_WIDGET),
993            hub_for_status.page_version(ROUTE_DYNAMIC_PANEL),
994            tel.get_components_applied(),
995            tel.get_pages_applied(),
996            tel.get_rollbacks(),
997            tel.get_rejected(),
998            action_log.get(),
999        )
1000    };
1001    let column_tertiary_style: Style = style! {
1002        Width(Length::Percent(100.0))
1003        Gap(SPACE_MD)
1004    };
1005    let column_quaternary_style: Style = style! {
1006        Width(Length::Percent(100.0))
1007        Padding(Edges::all(SPACE_MD))
1008        Background(palette.get_muted())
1009        Border::new(geometry.get_border_width(), palette.get_border())
1010        Radius(geometry.get_radius_md())
1011        Overflow::Hidden
1012    };
1013    let text_tertiary_style: Style = style! {
1014        Width(Length::Percent(100.0))
1015        FontSize(13.0)
1016        TextColor(palette.get_foreground())
1017    };
1018    let text_quaternary_style: Style = style! {
1019        Width(Length::Percent(100.0))
1020        FontSize(12.0)
1021        FontFamily::Monospace
1022        TextColor(palette.get_muted_foreground())
1023    };
1024    view! {
1025        EuvCard {
1026            title: DYNAMIC_PAGE_CARD_TITLE.to_string()
1027            tokens: tokens
1028            subtitle: DYNAMIC_PAGE_CARD_SUB
1029            column {
1030                style: column_tertiary_style
1031                EuvActionRow {
1032                    EuvButton {
1033                        label: BTN_UPDATE_PAGE_V1.to_string()
1034                        tokens: tokens
1035                        on_click: on_update_page
1036                    }
1037                    EuvButton {
1038                        label: BTN_APPLY_BUNDLE.to_string()
1039                        tokens: tokens
1040                        outline()
1041                        on_click: on_apply_bundle
1042                    }
1043                    EuvButton {
1044                        label: BTN_ROLLBACK_PAGE.to_string()
1045                        tokens: tokens
1046                        outline()
1047                        on_click: on_rollback_page
1048                    }
1049                    EuvButton {
1050                        label: BTN_INJECT_ROUTE.to_string()
1051                        tokens: tokens
1052                        outline()
1053                        on_click: on_inject_route
1054                    }
1055                }
1056                page_slot {
1057                    route: ROUTE_DYNAMIC_PANEL
1058                    column {
1059                        style: column_quaternary_style
1060                        text {
1061                            style: text_tertiary_style
1062                            { DYNAMIC_PAGE_FALLBACK }
1063                        }
1064                    }
1065                }
1066                text {
1067                    style: text_quaternary_style
1068                    { versions_text }
1069                }
1070            }
1071        }
1072    }
1073}
1074
1075/// Decodes minimal URL percent-encoding (`%XX` and `+`) inside `euv://hot-update?...` query parameters.
1076///
1077/// # Arguments
1078///
1079/// - `&str` - Raw query parameter value.
1080///
1081/// # Returns
1082///
1083/// - `String` - Decoded UTF-8 parameter string.
1084fn decode_hot_update_query_value(raw: &str) -> String {
1085    let bytes: &[u8] = raw.as_bytes();
1086    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
1087    let mut idx: usize = 0;
1088    while idx < bytes.len() {
1089        if bytes[idx] == b'%' && idx + 2 < bytes.len() {
1090            let h1: Option<u8> = (bytes[idx + 1] as char).to_digit(16).map(|v: u32| v as u8);
1091            let h2: Option<u8> = (bytes[idx + 2] as char).to_digit(16).map(|v: u32| v as u8);
1092            if let (Some(a), Some(b)) = (h1, h2) {
1093                out.push((a << 4) | b);
1094                idx += 3;
1095                continue;
1096            }
1097        } else if bytes[idx] == b'+' {
1098            out.push(b' ');
1099            idx += 1;
1100            continue;
1101        }
1102        out.push(bytes[idx]);
1103        idx += 1;
1104    }
1105    String::from_utf8_lossy(&out).into_owned()
1106}
1107
1108/// Automatically restores offline cached hot updates and connects the live SSE worker on native startup when configured by environment variables.
1109///
1110/// # Arguments
1111///
1112/// - `&DynamicUpdateHub` - Shared application dynamic update hub.
1113pub(crate) fn bootstrap_showcase_hot_updates(hub: &DynamicUpdateHub) {
1114    #[cfg(not(target_arch = "wasm32"))]
1115    {
1116        let has_server_env: bool = env::var(ENV_EUV_UPDATE_URL)
1117            .ok()
1118            .is_some_and(|v: String| !v.trim().is_empty());
1119        let env_cfg: HotUpdateProxyConfig = resolve_proxy_env();
1120        let has_cache_dir: bool = env_cfg.cache_dir_path().is_some();
1121        if !has_server_env && !has_cache_dir {
1122            return;
1123        }
1124        let client_cfg: UpdateClientConfig = env_cfg.to_client_config(
1125            DYNAMIC_PROXY_PROJECT.to_string(),
1126            WASM_SHOWCASE_SIGNING_KEY.as_bytes().to_vec(),
1127        );
1128        if has_server_env {
1129            let _: Result<(), DynamicReleaseError> = hub.connect_hot_updates(client_cfg);
1130        } else {
1131            let _: Result<Option<PreparedReleaseCandidate>, DynamicReleaseError> =
1132                hub.restore_cached_hot_updates(&client_cfg);
1133        }
1134    }
1135    #[cfg(target_arch = "wasm32")]
1136    {
1137        let _: &DynamicUpdateHub = hub;
1138    }
1139}
1140
1141/// Applies a live `euv://hot-update?server=...&proxy=...&channel=...&open=1` deep link to `hub`, returning whether `/dynamic` should be opened.
1142///
1143/// # Arguments
1144///
1145/// - `&DynamicUpdateHub` - Shared application dynamic update hub.
1146/// - `&str` - Raw query string following `?`.
1147///
1148/// # Returns
1149///
1150/// - `bool` - `true` when the deep link requested navigating to `/dynamic`.
1151pub(crate) fn apply_hot_update_deep_link(hub: &DynamicUpdateHub, query: &str) -> bool {
1152    let env_cfg: HotUpdateProxyConfig = resolve_proxy_env();
1153    let mut server: Option<String> = None;
1154    let mut proxy: Option<String> = env_cfg.proxy_url_str().map(str::to_string);
1155    let mut channel: String = env_cfg.get_channel().clone();
1156    let mut open_dynamic: bool = false;
1157    for pair in query.split('&') {
1158        let Some((raw_k, raw_v)) = pair.split_once('=') else {
1159            continue;
1160        };
1161        let key: &str = raw_k.trim();
1162        let val: String = decode_hot_update_query_value(raw_v.trim());
1163        if key == DEEP_LINK_PARAM_SERVER {
1164            let trimmed: &str = val.trim();
1165            if trimmed.is_empty() {
1166                server = Some(String::new());
1167            } else {
1168                server = Some(trimmed.to_string());
1169            }
1170        } else if key == DEEP_LINK_PARAM_PROXY {
1171            let trimmed: &str = val.trim();
1172            proxy = if trimmed.is_empty() {
1173                None
1174            } else {
1175                Some(trimmed.to_string())
1176            };
1177        } else if key == DEEP_LINK_PARAM_CHANNEL && !val.trim().is_empty() {
1178            channel = val.trim().to_string();
1179        } else if key == DEEP_LINK_PARAM_OPEN {
1180            open_dynamic = val == "1" || val.eq_ignore_ascii_case(DEEP_LINK_TRUE_VALUE);
1181        }
1182    }
1183    if let Some(srv) = server {
1184        if srv.is_empty() {
1185            hub.disconnect_hot_updates();
1186            return open_dynamic;
1187        }
1188        let cfg: HotUpdateProxyConfig =
1189            HotUpdateProxyConfig::new(srv, proxy, None, channel, true, DEFAULT_POLL_FALLBACK_SECS)
1190                .with_cache_dir(env_cfg.cache_dir_path().map(Path::to_path_buf));
1191        let client_cfg: UpdateClientConfig = cfg.to_client_config(
1192            DYNAMIC_PROXY_PROJECT.to_string(),
1193            WASM_SHOWCASE_SIGNING_KEY.as_bytes().to_vec(),
1194        );
1195        let _: Result<(), DynamicReleaseError> = hub.connect_hot_updates(client_cfg);
1196    } else if !hub.is_hot_updates_connected() {
1197        let client_cfg: UpdateClientConfig = env_cfg.to_client_config(
1198            DYNAMIC_PROXY_PROJECT.to_string(),
1199            WASM_SHOWCASE_SIGNING_KEY.as_bytes().to_vec(),
1200        );
1201        let _: Result<(), DynamicReleaseError> = hub.connect_hot_updates(client_cfg);
1202    } else {
1203        let _: bool = hub.request_hot_update_reconcile();
1204    }
1205    open_dynamic
1206}
1207
1208/// Reads a persisted hot-update preference from browser `localStorage` on `wasm32`.
1209///
1210/// # Arguments
1211///
1212/// - `&str` - Storage key name.
1213///
1214/// # Returns
1215///
1216/// - `Option<String>` - Stored non-empty string if present.
1217#[cfg(target_arch = "wasm32")]
1218fn read_hot_update_storage(key: &str) -> Option<String> {
1219    window()
1220        .and_then(|win: Window| win.local_storage().ok().flatten())
1221        .and_then(|storage: Storage| storage.get_item(key).ok().flatten())
1222        .map(|val: String| val.trim().to_string())
1223        .filter(|val: &String| !val.is_empty())
1224}
1225
1226/// Persists a hot-update preference into browser `localStorage` on `wasm32`.
1227///
1228/// # Arguments
1229///
1230/// - `&str` - Storage key name.
1231/// - `&str` - Value to store (empty string removes the key).
1232#[cfg(target_arch = "wasm32")]
1233fn write_hot_update_storage(key: &str, value: &str) {
1234    if let Some(storage) = window().and_then(|win: Window| win.local_storage().ok().flatten()) {
1235        let trimmed: &str = value.trim();
1236        if trimmed.is_empty() {
1237            let _: Result<(), JsValue> = storage.remove_item(key);
1238        } else {
1239            let _: Result<(), JsValue> = storage.set_item(key, trimmed);
1240        }
1241    }
1242}
1243
1244/// Executes a CORS browser `fetch()` request on `wasm32` and validates an HTTP 2xx response.
1245///
1246/// # Arguments
1247///
1248/// - `&str` - Target HTTP or HTTPS URL.
1249///
1250/// # Returns
1251///
1252/// - `Result<Response, String>` - Successful `Response` or formatted error string.
1253#[cfg(target_arch = "wasm32")]
1254async fn fetch_web_response(url: &str) -> Result<Response, String> {
1255    let win: Window = window().ok_or_else(|| WEB_OTA_ERR_NO_WINDOW.to_string())?;
1256    let opts: RequestInit = RequestInit::new();
1257    opts.set_mode(RequestMode::Cors);
1258    let promise: Promise = win.fetch_with_str_and_init(url, &opts);
1259    let resp_val: JsValue = JsFuture::from(promise)
1260        .await
1261        .map_err(|err: JsValue| format!("{WEB_OTA_ERR_FETCH}: {err:?}"))?;
1262    let resp: Response = resp_val
1263        .dyn_into::<Response>()
1264        .map_err(|_| WEB_OTA_ERR_FETCH.to_string())?;
1265    if !resp.ok() {
1266        return Err(format!("HTTP {}", resp.status()));
1267    }
1268    Ok(resp)
1269}
1270
1271/// Fetches a UTF-8 response body over browser `fetch()` on `wasm32`.
1272///
1273/// # Arguments
1274///
1275/// - `&str` - Target HTTP or HTTPS URL.
1276///
1277/// # Returns
1278///
1279/// - `Result<String, String>` - Response text payload or error string.
1280#[cfg(target_arch = "wasm32")]
1281async fn fetch_web_text(url: &str) -> Result<String, String> {
1282    let resp: Response = fetch_web_response(url).await?;
1283    let text_promise: Promise = resp
1284        .text()
1285        .map_err(|err: JsValue| format!("{WEB_OTA_ERR_FETCH}: {err:?}"))?;
1286    let text_val: JsValue = JsFuture::from(text_promise)
1287        .await
1288        .map_err(|err: JsValue| format!("{WEB_OTA_ERR_FETCH}: {err:?}"))?;
1289    text_val
1290        .as_string()
1291        .ok_or_else(|| WEB_OTA_ERR_FETCH.to_string())
1292}
1293
1294/// Fetches raw binary bytes over browser `fetch()` on `wasm32`.
1295///
1296/// # Arguments
1297///
1298/// - `&str` - Target HTTP or HTTPS URL.
1299///
1300/// # Returns
1301///
1302/// - `Result<Vec<u8>, String>` - Raw response bytes or error string.
1303#[cfg(target_arch = "wasm32")]
1304async fn fetch_web_bytes(url: &str) -> Result<Vec<u8>, String> {
1305    let resp: Response = fetch_web_response(url).await?;
1306    let buf_promise: Promise = resp
1307        .array_buffer()
1308        .map_err(|err: JsValue| format!("{WEB_OTA_ERR_FETCH}: {err:?}"))?;
1309    let buf_val: JsValue = JsFuture::from(buf_promise)
1310        .await
1311        .map_err(|err: JsValue| format!("{WEB_OTA_ERR_FETCH}: {err:?}"))?;
1312    Ok(Uint8Array::new(&buf_val).to_vec())
1313}
1314
1315/// Asynchronously fetches, HMAC-verifies, SHA-256-verifies, warms, and atomically applies the latest hot-update release in the browser on `wasm32`.
1316///
1317/// # Arguments
1318///
1319/// - `DynamicUpdateHub` - Target live dynamic update hub.
1320/// - `HotUpdateProxyConfig` - Active browser hot-update URL and channel configuration.
1321/// - `Signal<String>` - Live status detail message signal.
1322#[cfg(target_arch = "wasm32")]
1323fn spawn_web_hot_update_pull(
1324    hub: DynamicUpdateHub,
1325    cfg: HotUpdateProxyConfig,
1326    detail_sig: Signal<String>,
1327) {
1328    spawn_local(async move {
1329        let web_base: String = cfg.effective_web_base_url();
1330        let channel: String = cfg.get_channel().clone();
1331        let manifest_url: String = format!(
1332            "{web_base}/v1/projects/{DYNAMIC_PROXY_PROJECT}/channels/{channel}/manifest?protocol={DYNAMIC_PROTOCOL_VERSION_V1}&abi={DYNAMIC_HOST_ABI_V1}&mode={WEB_OTA_MODE_QUERY}"
1333        );
1334        let manifest_json: String = match fetch_web_text(&manifest_url).await {
1335            Ok(text) => text,
1336            Err(err) => {
1337                let mut st: HotUpdateLiveStatus = hub.hot_update_status_signal().get_untracked();
1338                let _: &mut HotUpdateLiveStatus = st.set_last_error(err.clone());
1339                hub.update_hot_update_status(st);
1340                let _: bool = detail_sig.set(format!("{WEB_OTA_ERR_MANIFEST}: {err}"));
1341                return;
1342            }
1343        };
1344        let manifest: ReleaseManifest = match parse_release_manifest_json(&manifest_json) {
1345            Ok(parsed) => parsed,
1346            Err(err) => {
1347                let msg: String = err.to_string();
1348                let mut st: HotUpdateLiveStatus = hub.hot_update_status_signal().get_untracked();
1349                let _: &mut HotUpdateLiveStatus = st.set_last_error(msg.clone());
1350                hub.update_hot_update_status(st);
1351                let _: bool = detail_sig.set(msg);
1352                return;
1353            }
1354        };
1355        let cur_seq: u64 = hub
1356            .hot_update_status_signal()
1357            .get_untracked()
1358            .get_active_release_seq();
1359        if manifest.get_release_seq() <= cur_seq {
1360            let _: bool = detail_sig.set(format!(
1361                "{WEB_OTA_UP_TO_DATE_PREFIX} v{cur_seq} ({channel})"
1362            ));
1363            return;
1364        }
1365        let mut blobs: BTreeMap<String, Vec<u8>> = BTreeMap::new();
1366        for sha in manifest.all_blob_hashes().into_iter() {
1367            let blob_url: String = format!("{web_base}/v1/blobs/{sha}");
1368            match fetch_web_bytes(&blob_url).await {
1369                Ok(bytes) => {
1370                    let _: Option<Vec<u8>> = blobs.insert(sha, bytes);
1371                }
1372                Err(err) => {
1373                    let mut st: HotUpdateLiveStatus =
1374                        hub.hot_update_status_signal().get_untracked();
1375                    let _: &mut HotUpdateLiveStatus = st.set_last_error(err.clone());
1376                    hub.update_hot_update_status(st);
1377                    let _: bool = detail_sig.set(format!("{WEB_OTA_ERR_BLOB}: {err}"));
1378                    return;
1379                }
1380            }
1381        }
1382        let client_cfg: UpdateClientConfig = cfg.to_client_config(
1383            DYNAMIC_PROXY_PROJECT.to_string(),
1384            WASM_SHOWCASE_SIGNING_KEY.as_bytes().to_vec(),
1385        );
1386        let candidate: PreparedReleaseCandidate =
1387            match prepare_verified_release_from_blobs(&client_cfg, &manifest_json, &blobs) {
1388                Ok(cand) => cand,
1389                Err(err) => {
1390                    let msg: String = err.to_string();
1391                    let mut st: HotUpdateLiveStatus =
1392                        hub.hot_update_status_signal().get_untracked();
1393                    let _: &mut HotUpdateLiveStatus = st.set_last_error(msg.clone());
1394                    hub.update_hot_update_status(st);
1395                    let _: bool = detail_sig.set(msg);
1396                    return;
1397                }
1398            };
1399        match hub.apply_prepared_release(&candidate) {
1400            Ok(_) => {
1401                let seq: u64 = candidate.get_manifest().get_release_seq();
1402                let full_sha: String = candidate.get_manifest_sha256().clone();
1403                let short_sha: String = full_sha.chars().take(12).collect::<String>();
1404                let mut st: HotUpdateLiveStatus = hub.hot_update_status_signal().get_untracked();
1405                let next_applied: u64 = st.get_applied_count().saturating_add(1);
1406                let _: &mut HotUpdateLiveStatus = st
1407                    .set_active_release_seq(seq)
1408                    .set_active_manifest_sha256(full_sha)
1409                    .set_applied_count(next_applied)
1410                    .set_restored_from_cache(false)
1411                    .set_pending_safe_boundary(false)
1412                    .set_last_error(String::new());
1413                hub.update_hot_update_status(st);
1414                let _: bool = detail_sig.set(format!(
1415                    "{WEB_OTA_APPLIED_PREFIX} v{seq} (sha256={short_sha}..)"
1416                ));
1417            }
1418            Err(err) => {
1419                let msg: String = err.to_string();
1420                let mut st: HotUpdateLiveStatus = hub.hot_update_status_signal().get_untracked();
1421                let _: &mut HotUpdateLiveStatus = st.set_last_error(msg.clone());
1422                hub.update_hot_update_status(st);
1423                let _: bool = detail_sig.set(msg);
1424            }
1425        }
1426    });
1427}
1428
1429/// Mounts the Proxy-Aware On-Device Hot Update control card connected to `euv update serve` + `DynamicUpdateHub`.
1430///
1431/// # Arguments
1432///
1433/// - `&ShowcaseState` - Shared showcase state.
1434/// - `ThemeTokens` - Active design tokens.
1435///
1436/// # Returns
1437///
1438/// - `NodeId` - Mounted proxy hot-update card node.
1439pub(crate) fn mount_dynamic_proxy_hot_update_card(
1440    state: &ShowcaseState,
1441    tokens: ThemeTokens,
1442) -> NodeId {
1443    let palette: ThemePalette = tokens.get_palette();
1444    let geometry: ThemeGeometry = tokens.get_geometry();
1445    let hub: DynamicUpdateHub = state.get_dynamic_hub().clone();
1446    let live_status_sig: Signal<HotUpdateLiveStatus> = hub.hot_update_status_signal();
1447    let init_live: HotUpdateLiveStatus = live_status_sig.get_untracked();
1448    let env_cfg: HotUpdateProxyConfig = resolve_proxy_env();
1449    let cache_dir_opt: Option<PathBuf> = env_cfg.cache_dir_path().map(Path::to_path_buf);
1450    #[cfg(target_arch = "wasm32")]
1451    let init_server: String = if !init_live.get_server_url().is_empty() {
1452        init_live.get_server_url().clone()
1453    } else {
1454        read_hot_update_storage(DYNAMIC_LS_SERVER_KEY)
1455            .unwrap_or_else(|| env_cfg.get_server_url().clone())
1456    };
1457    #[cfg(not(target_arch = "wasm32"))]
1458    let init_server: String = if !init_live.get_server_url().is_empty() {
1459        init_live.get_server_url().clone()
1460    } else {
1461        env_cfg.get_server_url().clone()
1462    };
1463    #[cfg(target_arch = "wasm32")]
1464    let init_proxy: String = if !init_live.get_proxy_url().is_empty() {
1465        init_live.get_proxy_url().clone()
1466    } else {
1467        read_hot_update_storage(DYNAMIC_LS_PROXY_KEY)
1468            .or_else(|| env_cfg.proxy_url_str().map(str::to_string))
1469            .unwrap_or_default()
1470    };
1471    #[cfg(not(target_arch = "wasm32"))]
1472    let init_proxy: String = if !init_live.get_proxy_url().is_empty() {
1473        init_live.get_proxy_url().clone()
1474    } else {
1475        env_cfg
1476            .proxy_url_str()
1477            .map(str::to_string)
1478            .unwrap_or_default()
1479    };
1480    let channel_name: String = if !init_live.get_channel().is_empty() {
1481        init_live.get_channel().clone()
1482    } else {
1483        env_cfg.get_channel().clone()
1484    };
1485    let server_sig: Signal<String> = Signal::new(init_server);
1486    let proxy_sig: Signal<String> = Signal::new(init_proxy);
1487    let detail_sig: Signal<String> = Signal::new(DYNAMIC_PROXY_IDLE_DETAIL.to_string());
1488    #[cfg(target_arch = "wasm32")]
1489    let web_sse_slot: Rc<RefCell<Option<(EventSource, Closure<dyn FnMut(MessageEvent)>)>>> =
1490        Rc::new(RefCell::new(None));
1491    #[cfg(target_arch = "wasm32")]
1492    {
1493        let s_persist: Signal<String> = server_sig;
1494        let p_persist: Signal<String> = proxy_sig;
1495        let _: Effect = Effect::new(move || {
1496            let next_srv: String = s_persist.get();
1497            write_hot_update_storage(DYNAMIC_LS_SERVER_KEY, &next_srv);
1498            let next_prx: String = p_persist.get();
1499            write_hot_update_storage(DYNAMIC_LS_PROXY_KEY, &next_prx);
1500        });
1501    }
1502    let ch_toggle: String = channel_name.clone();
1503    let hub_pull: DynamicUpdateHub = hub.clone();
1504    let ch_pull: String = channel_name.clone();
1505    let cache_pull: Option<PathBuf> = cache_dir_opt.clone();
1506    let on_pull_now = move |_: &UiEvent| {
1507        #[cfg(not(target_arch = "wasm32"))]
1508        {
1509            if hub_pull.request_hot_update_reconcile() {
1510                let _: bool = detail_sig.set(DYNAMIC_PROXY_RECONCILE_SENT_MSG.to_string());
1511                return;
1512            }
1513            let srv: String = server_sig.get_untracked();
1514            let prx: String = proxy_sig.get_untracked();
1515            let prx_opt: Option<String> = if prx.trim().is_empty() {
1516                None
1517            } else {
1518                Some(prx.trim().to_string())
1519            };
1520            let config_spec: HotUpdateProxyConfig = HotUpdateProxyConfig::new(
1521                srv,
1522                prx_opt,
1523                None,
1524                ch_pull.clone(),
1525                true,
1526                DEFAULT_POLL_FALLBACK_SECS,
1527            )
1528            .with_cache_dir(cache_pull.clone());
1529            let client_cfg: UpdateClientConfig = config_spec.to_client_config(
1530                DYNAMIC_PROXY_PROJECT.to_string(),
1531                WASM_SHOWCASE_SIGNING_KEY.as_bytes().to_vec(),
1532            );
1533            match hub_pull.connect_hot_updates(client_cfg) {
1534                Ok(()) => {
1535                    let _: bool = detail_sig.set(DYNAMIC_PROXY_RECONCILE_SENT_MSG.to_string());
1536                }
1537                Err(err) => {
1538                    let _: bool = detail_sig.set(err.to_string());
1539                }
1540            }
1541        }
1542        #[cfg(target_arch = "wasm32")]
1543        {
1544            let _: &Option<PathBuf> = &cache_pull;
1545            let srv: String = server_sig.get_untracked();
1546            let prx: String = proxy_sig.get_untracked();
1547            let prx_opt: Option<String> = if prx.trim().is_empty() {
1548                None
1549            } else {
1550                Some(prx.trim().to_string())
1551            };
1552            let active_config: HotUpdateProxyConfig = HotUpdateProxyConfig::new(
1553                srv,
1554                prx_opt,
1555                None,
1556                ch_pull.clone(),
1557                true,
1558                DEFAULT_POLL_FALLBACK_SECS,
1559            );
1560            spawn_web_hot_update_pull(hub_pull.clone(), active_config, detail_sig);
1561        }
1562    };
1563    let hub_rb: DynamicUpdateHub = hub.clone();
1564    let on_rollback_hot = move |_: &UiEvent| {
1565        let page_rb: bool = hub_rb.rollback_page(ROUTE_DYNAMIC_PANEL).is_ok();
1566        let comp_rb: bool = hub_rb.rollback_component(SLOT_PROMO_BANNER).is_ok();
1567        if page_rb || comp_rb {
1568            let _: bool = detail_sig.set(DYNAMIC_PROXY_ROLLBACK_OK_MSG.to_string());
1569        } else {
1570            let _: bool = detail_sig.set(DYNAMIC_PROXY_ROLLBACK_EMPTY_MSG.to_string());
1571        }
1572    };
1573    let ch_badge: String = channel_name;
1574    let status_badge_text = move || -> String {
1575        let st: HotUpdateLiveStatus = live_status_sig.get();
1576        let prx: String = if !st.get_proxy_url().is_empty() {
1577            st.get_proxy_url().clone()
1578        } else {
1579            proxy_sig.get()
1580        };
1581        let mode: &str = if !st.get_connected() {
1582            if st.get_restored_from_cache() {
1583                DYNAMIC_PROXY_MODE_OFFLINE_CACHE
1584            } else {
1585                DYNAMIC_PROXY_MODE_OFF
1586            }
1587        } else if !st.get_sse_live() {
1588            if st.get_restored_from_cache() || st.get_active_release_seq() > 0 {
1589                DYNAMIC_PROXY_MODE_OFFLINE_CACHE
1590            } else {
1591                DYNAMIC_PROXY_MODE_CONNECTING
1592            }
1593        } else if prx.trim().is_empty() {
1594            DYNAMIC_PROXY_MODE_DIRECT
1595        } else {
1596            DYNAMIC_PROXY_MODE_PROXY
1597        };
1598        let ch: &str = if st.get_channel().is_empty() {
1599            ch_badge.as_str()
1600        } else {
1601            st.get_channel().as_str()
1602        };
1603        let sha_short: String = if st.get_active_manifest_sha256().is_empty() {
1604            DYNAMIC_PROXY_SHA_NONE.to_string()
1605        } else {
1606            st.get_active_manifest_sha256()
1607                .chars()
1608                .take(12)
1609                .collect::<String>()
1610        };
1611        let cache_tag: &str = if st.get_restored_from_cache() {
1612            DYNAMIC_PROXY_CACHE_TAG
1613        } else {
1614            ""
1615        };
1616        let defer_tag: &str = if st.get_pending_safe_boundary() {
1617            DYNAMIC_PROXY_DEFERRED_TAG
1618        } else {
1619            ""
1620        };
1621        format!(
1622            "State: {mode} | Channel: {ch} | Version: v{} | SHA-256: {sha_short}{cache_tag}{defer_tag}",
1623            st.get_active_release_seq()
1624        )
1625    };
1626    let detail_text = move || -> String {
1627        let st: HotUpdateLiveStatus = live_status_sig.get();
1628        if st.get_active_release_seq() > 0 {
1629            let short_sha: String = st
1630                .get_active_manifest_sha256()
1631                .chars()
1632                .take(12)
1633                .collect::<String>();
1634            let cache_note: &str = if st.get_restored_from_cache() {
1635                DYNAMIC_PROXY_CACHE_TAG
1636            } else {
1637                ""
1638            };
1639            return format!(
1640                "Active verified release v{} (sha256={short_sha}.., applied={}{cache_note})",
1641                st.get_active_release_seq(),
1642                st.get_applied_count()
1643            );
1644        }
1645        if !st.get_last_error().is_empty() {
1646            return st.get_last_error().clone();
1647        }
1648        if st.get_sse_live() {
1649            return DYNAMIC_PROXY_WAITING_RELEASE_MSG.to_string();
1650        }
1651        detail_sig.get()
1652    };
1653    let hub_slot: DynamicUpdateHub = hub;
1654    let ch_slot: String = ch_toggle;
1655    let cache_slot: Option<PathBuf> = cache_dir_opt;
1656    #[cfg(target_arch = "wasm32")]
1657    let web_sse_btn: Rc<RefCell<Option<(EventSource, Closure<dyn FnMut(MessageEvent)>)>>> =
1658        Rc::clone(&web_sse_slot);
1659    let connect_btn_slot = move || -> Vec<NodeId> {
1660        let is_conn: bool = live_status_sig.get().get_connected();
1661        let label: String = if is_conn {
1662            DYNAMIC_PROXY_BTN_DISCONNECT.to_string()
1663        } else {
1664            DYNAMIC_PROXY_BTN_CONNECT.to_string()
1665        };
1666        let hub_cb: DynamicUpdateHub = hub_slot.clone();
1667        let ch_cb: String = ch_slot.clone();
1668        let cache_cb: Option<PathBuf> = cache_slot.clone();
1669        #[cfg(target_arch = "wasm32")]
1670        let sse_cb: Rc<RefCell<Option<(EventSource, Closure<dyn FnMut(MessageEvent)>)>>> =
1671            Rc::clone(&web_sse_btn);
1672        let on_toggle_click = move |_: &UiEvent| {
1673            if live_status_sig.get_untracked().get_connected() {
1674                #[cfg(target_arch = "wasm32")]
1675                if let Ok(mut guard) = sse_cb.try_borrow_mut()
1676                    && let Some((es, _)) = guard.take()
1677                {
1678                    es.close();
1679                }
1680                hub_cb.disconnect_hot_updates();
1681                let _: bool = detail_sig.set(DYNAMIC_PROXY_DISCONNECTED_MSG.to_string());
1682                return;
1683            }
1684            let srv: String = server_sig.get_untracked();
1685            let prx: String = proxy_sig.get_untracked();
1686            let prx_opt: Option<String> = if prx.trim().is_empty() {
1687                None
1688            } else {
1689                Some(prx.trim().to_string())
1690            };
1691            let config_spec_primary: HotUpdateProxyConfig = HotUpdateProxyConfig::new(
1692                srv,
1693                prx_opt.clone(),
1694                None,
1695                ch_cb.clone(),
1696                true,
1697                DEFAULT_POLL_FALLBACK_SECS,
1698            )
1699            .with_cache_dir(cache_cb.clone());
1700            #[cfg(not(target_arch = "wasm32"))]
1701            {
1702                let client_cfg: UpdateClientConfig = config_spec_primary.to_client_config(
1703                    DYNAMIC_PROXY_PROJECT.to_string(),
1704                    WASM_SHOWCASE_SIGNING_KEY.as_bytes().to_vec(),
1705                );
1706                match hub_cb.connect_hot_updates(client_cfg) {
1707                    Ok(()) => {
1708                        let _: bool = detail_sig.set(format!(
1709                            "{}/v1/projects/{DYNAMIC_PROXY_PROJECT}/channels/{ch_cb}/events",
1710                            config_spec_primary.get_server_url()
1711                        ));
1712                    }
1713                    Err(err) => {
1714                        let _: bool = detail_sig.set(err.to_string());
1715                    }
1716                }
1717            }
1718            #[cfg(target_arch = "wasm32")]
1719            {
1720                let web_base: String = config_spec_primary.effective_web_base_url();
1721                let events_url: String = format!(
1722                    "{web_base}/v1/projects/{DYNAMIC_PROXY_PROJECT}/channels/{ch_cb}/events?protocol={DYNAMIC_PROTOCOL_VERSION_V1}&abi={DYNAMIC_HOST_ABI_V1}&mode={WEB_OTA_MODE_QUERY}"
1723                );
1724                match EventSource::new(&events_url) {
1725                    Ok(es) => {
1726                        let hub_ev: DynamicUpdateHub = hub_cb.clone();
1727                        let cfg_ev: HotUpdateProxyConfig = config_spec_primary.clone();
1728                        let on_release: Closure<dyn FnMut(MessageEvent)> =
1729                            Closure::new(move |_: MessageEvent| {
1730                                spawn_web_hot_update_pull(
1731                                    hub_ev.clone(),
1732                                    cfg_ev.clone(),
1733                                    detail_sig,
1734                                );
1735                            });
1736                        let _: Result<(), JsValue> = es.add_event_listener_with_callback(
1737                            SSE_EVENT_RELEASE_ACTIVATED,
1738                            on_release.as_ref().unchecked_ref(),
1739                        );
1740                        if let Ok(mut guard) = sse_cb.try_borrow_mut() {
1741                            if let Some((prev_es, _)) = guard.take() {
1742                                prev_es.close();
1743                            }
1744                            *guard = Some((es, on_release));
1745                        }
1746                        let mut st: HotUpdateLiveStatus = live_status_sig.get_untracked();
1747                        let _: &mut HotUpdateLiveStatus = st
1748                            .set_connected(true)
1749                            .set_sse_live(true)
1750                            .set_server_url(config_spec_primary.get_server_url().clone())
1751                            .set_proxy_url(prx_opt.unwrap_or_default())
1752                            .set_channel(ch_cb.clone())
1753                            .set_last_error(String::new());
1754                        hub_cb.update_hot_update_status(st);
1755                        let _: bool =
1756                            detail_sig.set(format!("{WEB_OTA_SSE_CONNECTED_PREFIX} {events_url}"));
1757                        spawn_web_hot_update_pull(hub_cb.clone(), config_spec_primary, detail_sig);
1758                    }
1759                    Err(err) => {
1760                        let _: bool = detail_sig.set(format!("{WEB_OTA_SSE_ERR_PREFIX} {err:?}"));
1761                    }
1762                }
1763            }
1764        };
1765        let btn_fill: Style = style! {
1766            Width(Length::Percent(100.0))
1767        };
1768        let node_id: NodeId = view! {
1769            EuvButton {
1770                label: label
1771                tokens: tokens
1772                style: btn_fill
1773                on_click: on_toggle_click
1774            }
1775        };
1776        vec![node_id]
1777    };
1778    let column_style: Style = style! {
1779        Width(Length::Percent(100.0))
1780        Gap(SPACE_MD)
1781        Overflow::Hidden
1782    };
1783    let row_style: Style = style! {
1784        FlexGrow(1.0)
1785        MinWidth(Length::Px(0.0))
1786        AlignItems::Center
1787    };
1788    let live_slot_label_style: Style = style! {
1789        Width(Length::Percent(100.0))
1790        FontSize(11.5)
1791        FontWeight::SemiBold
1792        TextColor(palette.get_muted_foreground())
1793    };
1794    let live_slot_box_style: Style = style! {
1795        Width(Length::Percent(100.0))
1796        Padding(Edges::all(SPACE_SM))
1797        Background(palette.get_muted())
1798        Border::new(geometry.get_border_width(), palette.get_border())
1799        Radius(geometry.get_radius_sm())
1800        Overflow::Hidden
1801    };
1802    let live_slot_text_style: Style = style! {
1803        Width(Length::Percent(100.0))
1804        FontSize(12.5)
1805        TextColor(palette.get_foreground())
1806    };
1807    let column_secondary_style: Style = style! {
1808        Width(Length::Percent(100.0))
1809        Padding(Edges::all(SPACE_SM))
1810        Gap(SPACE_XS)
1811        Background(palette.get_muted())
1812        Border::new(geometry.get_border_width(), palette.get_border())
1813        Radius(geometry.get_radius_sm())
1814        Overflow::Hidden
1815    };
1816    let text_style: Style = style! {
1817        Width(Length::Percent(100.0))
1818        FontSize(12.0)
1819        FontWeight::SemiBold
1820        FontFamily::Monospace
1821        TextColor(palette.get_foreground())
1822    };
1823    let text_secondary_style: Style = style! {
1824        Width(Length::Percent(100.0))
1825        FontSize(12.0)
1826        TextColor(palette.get_muted_foreground())
1827    };
1828    view! {
1829        EuvCard {
1830            title: DYNAMIC_PROXY_CARD_TITLE.to_string()
1831            tokens: tokens
1832            subtitle: DYNAMIC_PROXY_CARD_SUB
1833            column {
1834                style: column_style
1835                text {
1836                    style: live_slot_label_style
1837                    { DYNAMIC_PROXY_LIVE_SLOT_LABEL }
1838                }
1839                slot {
1840                    id: SLOT_PROMO_BANNER
1841                    column {
1842                        style: live_slot_box_style
1843                        text {
1844                            style: live_slot_text_style
1845                            { DYNAMIC_SLOT_BANNER_FALLBACK }
1846                        }
1847                    }
1848                }
1849                column {
1850                    style: column_secondary_style
1851                    text {
1852                        style: text_style
1853                        { status_badge_text }
1854                    }
1855                    text {
1856                        style: text_secondary_style
1857                        { detail_text }
1858                    }
1859                }
1860                EuvInput {
1861                    value: server_sig
1862                    placeholder: DYNAMIC_PROXY_SERVER_PLACEHOLDER
1863                    tokens: tokens
1864                }
1865                EuvInput {
1866                    value: proxy_sig
1867                    placeholder: DYNAMIC_PROXY_URL_PLACEHOLDER
1868                    tokens: tokens
1869                }
1870                EuvActionRow {
1871                    row {
1872                        style: row_style
1873                        bind_children: connect_btn_slot
1874                    }
1875                    EuvButton {
1876                        label: DYNAMIC_PROXY_BTN_PULL.to_string()
1877                        tokens: tokens
1878                        outline()
1879                        on_click: on_pull_now
1880                    }
1881                    EuvButton {
1882                        label: DYNAMIC_PROXY_BTN_ROLLBACK.to_string()
1883                        tokens: tokens
1884                        outline()
1885                        on_click: on_rollback_hot
1886                    }
1887                }
1888            }
1889        }
1890    }
1891}
1892
1893/// Mounts the interactive component-level and page-level dynamic OTA updates showcase page.
1894///
1895/// # Arguments
1896///
1897/// - `&ShowcaseState` - Reactive showcase state.
1898/// - `ThemeTokens` - Active design tokens.
1899///
1900/// # Returns
1901///
1902/// - `NodeId` - Mounted dynamic updates page node.
1903pub fn mount_dynamic_page(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
1904    state.ensure_wasm_registry_loaded();
1905    let proxy_card: NodeId = mount_dynamic_proxy_hot_update_card(state, tokens);
1906    let partial_card: NodeId = mount_dynamic_partial_wasm_card(state, tokens);
1907    let global_card: NodeId = mount_dynamic_global_wasm_card(state, tokens);
1908    let fault_card: NodeId = mount_dynamic_fault_card(state, tokens);
1909    let comp_card: NodeId = mount_dynamic_component_card(state, tokens);
1910    let page_card: NodeId = mount_dynamic_page_slot_card(state, tokens);
1911    let wasm_grid: NodeId = mount_responsive_grid(vec![partial_card, global_card], 2);
1912    let slots_grid: NodeId = mount_responsive_grid(vec![comp_card, page_card], 2);
1913    view! {
1914        EuvPage {
1915            title: DYNAMIC_TITLE.to_string()
1916            subtitle: DYNAMIC_SUBTITLE.to_string()
1917            tokens: tokens
1918            { proxy_card }
1919            { slots_grid }
1920            { wasm_grid }
1921            { fault_card }
1922        }
1923    }
1924}