1#![allow(non_snake_case)]
2
3mod companion_device;
4
5use aether::prelude::*;
6use wasm_bindgen::prelude::*;
7use wasm_bindgen::JsCast;
8use web_sys::{MessageEvent, WebSocket};
9use wellfare_core::companion_pairing::MSG_CHALLENGE;
10use wellfare_core::companion_sync::{CompanionCsvFile, CompanionHealthBundle};
11
12fn main() {
13 aether::launch(App);
14}
15
16const OUTBOX_KEY: &str = "qualia-wellfair-health-outbox";
17
18#[wasm_bindgen(inline_js = r#"
19 export async function startQrScanner(videoElementId, onScanSuccess, onScanError) {
20 const video = document.getElementById(videoElementId);
21 if (!video) {
22 onScanError("Video element not found");
23 return;
24 }
25 if (!('BarcodeDetector' in window)) {
26 onScanError("Camera QR scan unavailable — enter the desktop WS URL manually.");
27 return;
28 }
29 try {
30 const stream = await navigator.mediaDevices.getUserMedia({
31 video: { facingMode: { ideal: "environment" } },
32 audio: false,
33 });
34 video.srcObject = stream;
35 await video.play();
36 const detector = new BarcodeDetector({ formats: ["qr_code"] });
37 const scan = async () => {
38 try {
39 const codes = await detector.detect(video);
40 if (codes.length > 0 && codes[0].rawValue) {
41 onScanSuccess(codes[0].rawValue);
42 stream.getTracks().forEach((t) => t.stop());
43 return;
44 }
45 } catch (_) {}
46 requestAnimationFrame(scan);
47 };
48 scan();
49 } catch (err) {
50 onScanError(String(err));
51 }
52 }
53
54 export async function requestDirectoryAccess() {
55 if (!('showDirectoryPicker' in window)) {
56 throw new Error("File System Access API not supported");
57 }
58 const dirHandle = await window.showDirectoryPicker({ mode: 'readwrite' });
59 console.log("Directory access granted:", dirHandle.name);
60 return true;
61 }
62
63 export async function readCsvFilesFromInput(inputId) {
64 const input = document.getElementById(inputId);
65 if (!input || !input.files || input.files.length === 0) {
66 return [];
67 }
68 const out = [];
69 for (const file of input.files) {
70 const text = await file.text();
71 out.push({ filename: file.name, csv_content: text });
72 }
73 return out;
74 }
75
76 export function persistOutbox(key, json) {
77 localStorage.setItem(key, json);
78 }
79
80 export function loadOutbox(key) {
81 return localStorage.getItem(key) || "";
82 }
83
84 export async function copyToClipboard(text) {
85 if (navigator.clipboard && navigator.clipboard.writeText) {
86 await navigator.clipboard.writeText(text);
87 return true;
88 }
89 return false;
90 }
91
92 export async function shareBundle(title, text) {
93 if (navigator.share) {
94 await navigator.share({ title, text });
95 return true;
96 }
97 return false;
98 }
99"#)]
100extern "C" {
101 fn startQrScanner(
102 video_id: &str,
103 on_success: &Closure<dyn FnMut(String)>,
104 on_error: &Closure<dyn FnMut(String)>,
105 );
106 #[wasm_bindgen(catch)]
107 async fn requestDirectoryAccess() -> Result<JsValue, JsValue>;
108 #[wasm_bindgen(catch)]
109 async fn readCsvFilesFromInput(input_id: &str) -> Result<JsValue, JsValue>;
110 fn persistOutbox(key: &str, json: &str);
111 fn loadOutbox(key: &str) -> String;
112 #[wasm_bindgen(catch)]
113 async fn copyToClipboard(text: &str) -> Result<JsValue, JsValue>;
114 #[wasm_bindgen(catch)]
115 async fn shareBundle(title: &str, text: &str) -> Result<JsValue, JsValue>;
116}
117
118#[derive(Clone, PartialEq)]
119enum AppState {
120 Initializing,
121 VaultInit,
122 Scanning,
123 ManualConnect,
124 Connecting(String),
125 Connected,
126 BundleReady { json: String, file_count: usize },
127 Error(String),
128}
129
130fn captured_at_unix() -> u32 {
131 (js_sys::Date::new_0().get_time() / 1000.0) as u32
132}
133
134fn build_bundle_from_files(files: Vec<CompanionCsvFile>) -> Result<String, String> {
135 let bundle =
136 CompanionHealthBundle::new(companion_device::device_id(), captured_at_unix(), files);
137 bundle.validate()?;
138 serde_json::to_string_pretty(&bundle).map_err(|e| e.to_string())
139}
140
141fn App() -> Element {
142 let mut state = use_signal(|| AppState::Initializing);
143 let mut ws_target = use_signal(|| String::new());
144 let mut ws_handle = use_signal(|| None::<WebSocket>);
145 let mut status_msg = use_signal(|| String::new());
146 let mut manual_ws_url = use_signal(|| String::new());
147 let file_input_id = "samsung-csv-picker";
148
149 use_effect(move || {
150 if *state.read() == AppState::Initializing {
151 let stored = loadOutbox(OUTBOX_KEY);
152 if !stored.is_empty() {
153 if let Ok(bundle) = serde_json::from_str::<CompanionHealthBundle>(&stored) {
154 let file_count = bundle.files.len();
155 state.set(AppState::BundleReady {
156 json: stored,
157 file_count,
158 });
159 status_msg.set("Restored health bundle from outbox.".into());
160 return;
161 }
162 }
163
164 let window = web_sys::window().unwrap();
165 let has_picker =
166 js_sys::Reflect::has(&window, &JsValue::from_str("showDirectoryPicker"))
167 .unwrap_or(false);
168
169 if has_picker {
170 state.set(AppState::VaultInit);
171 } else {
172 state.set(AppState::Scanning);
173 }
174 }
175 });
176
177 use_effect(move || {
178 if *state.read() == AppState::Scanning {
179 let on_success = Closure::wrap(Box::new(move |scanned_text: String| {
180 web_sys::console::log_1(&format!("Scanned QR: {}", scanned_text).into());
181 ws_target.set(scanned_text.clone());
182 state.set(AppState::Connecting(scanned_text));
183 }) as Box<dyn FnMut(String)>);
184 let mut status_msg_scan = status_msg.clone();
185 let on_error = Closure::wrap(Box::new(move |msg: String| {
186 status_msg_scan.set(msg);
187 state.set(AppState::ManualConnect);
188 }) as Box<dyn FnMut(String)>);
189
190 startQrScanner("qr-video-element", &on_success, &on_error);
191 on_success.forget();
192 on_error.forget();
193 }
194 });
195
196 use_effect(move || {
197 let connect_url = if let AppState::Connecting(ref url) = *state.read() {
198 Some(url.clone())
199 } else {
200 None
201 };
202
203 if let Some(url) = connect_url {
204 match WebSocket::new(&url) {
205 Ok(ws) => {
206 ws_handle.set(Some(ws.clone()));
207 let ws_clone = ws.clone();
208 let on_open = Closure::wrap(Box::new(move |_| {
209 web_sys::console::log_1(&"WebSocket Connected".into());
210 }) as Box<dyn FnMut(JsValue)>);
211 ws.set_onopen(Some(on_open.as_ref().unchecked_ref()));
212 on_open.forget();
213
214 let mut status_msg_ws = status_msg.clone();
215 let on_message = Closure::wrap(Box::new(move |e: MessageEvent| {
216 if let Ok(txt) = e.data().dyn_into::<js_sys::JsString>() {
217 let text: String = txt.into();
218 web_sys::console::log_1(
219 &format!("Received WS Message: {}", text).into(),
220 );
221
222 if text.contains(MSG_CHALLENGE) {
223 web_sys::console::log_1(
224 &"Signing Ed25519 pairing challenge...".into(),
225 );
226 match companion_device::build_pairing_response(&text) {
227 Ok(response_json) => {
228 let _ = ws_clone.send_with_str(&response_json);
229 }
230 Err(e) => {
231 status_msg_ws.set(format!("Pairing sign failed: {e}"));
232 state.set(AppState::Error(e));
233 }
234 }
235 } else if text.contains("AUTH_SUCCESS") {
236 state.set(AppState::Connected);
237 let pending = loadOutbox(OUTBOX_KEY);
238 if !pending.is_empty() {
239 let payload =
240 format!(r#"{{"type":"HEALTH_BUNDLE","bundle":{pending}}}"#);
241 let _ = ws_clone.send_with_str(&payload);
242 status_msg_ws
243 .set("Sent pending health bundle to desktop.".into());
244 }
245 } else if text.contains("AUTH_DENIED") {
246 status_msg_ws.set("Desktop denied pairing.".into());
247 state.set(AppState::Error("Pairing denied by desktop".into()));
248 } else if text.contains("HEALTH_BUNDLE_ACK") {
249 status_msg_ws.set("Desktop acknowledged health bundle.".into());
250 }
251 }
252 })
253 as Box<dyn FnMut(MessageEvent)>);
254 ws.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
255 on_message.forget();
256 }
257 Err(e) => {
258 state.set(AppState::Error(format!("WS Error: {:?}", e)));
259 }
260 }
261 }
262 });
263
264 rsx! {
265 div {
266 style: "display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; background-color: #1a1a1a; color: white; font-family: sans-serif; padding: 1rem;",
267
268 h1 { "Qualia Mobile Companion" }
269
270 match &*state.read() {
271 AppState::Initializing => rsx! {
272 div { p { "Initializing Fiduciary Boundary..." } }
273 },
274 AppState::VaultInit => rsx! {
275 div {
276 style: "text-align: center; max-width: 420px;",
277 h3 { "Private Vault Initialization" }
278 p { "Your device supports Tier-1 Edge capabilities." }
279 button {
280 style: "padding: 12px 24px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; font-size: 16px; margin-top: 16px;",
281 onclick: move |_| {
282 let mut state = state.clone();
283 spawn(async move {
284 match requestDirectoryAccess().await {
285 Ok(_) => state.set(AppState::Scanning),
286 Err(e) => web_sys::console::error_1(&e)
287 }
288 });
289 },
290 "Initialize Local Vault"
291 }
292 }
293 },
294 AppState::Scanning => rsx! {
295 div {
296 style: "text-align: center; max-width: 420px;",
297 h3 { "Scan Desktop QR Code" }
298 video {
299 id: "qr-video-element",
300 width: "100%",
301 height: "auto",
302 autoplay: true,
303 }
304 p { "Point your camera at the QR shown in desktop WellFair → Tools." }
305 button {
306 style: "margin-top: 0.75rem; padding: 8px 14px; background: #444; color: #fff; border: none; border-radius: 4px;",
307 onclick: move |_| state.set(AppState::ManualConnect),
308 "Enter URL manually"
309 }
310 }
311 },
312 AppState::ManualConnect => rsx! {
313 div {
314 style: "max-width: 420px; width: 100%;",
315 h3 { "Connect manually" }
316 p {
317 style: "font-size: 0.85rem; color: #ccc;",
318 "Copy the WebSocket URL from desktop WellFair pairing panel."
319 }
320 input {
321 r#type: "text",
322 value: "{manual_ws_url.read()}",
323 placeholder: "ws://192.168.x.x:8080/mobile/stream",
324 style: "width: 100%; padding: 10px; margin: 0.75rem 0; border-radius: 4px; border: 1px solid #555; background: #222; color: #fff;",
325 oninput: move |e| manual_ws_url.set(e.value()),
326 }
327 button {
328 style: "padding: 10px 16px; background: #2a6f97; color: white; border: none; border-radius: 4px;",
329 onclick: move |_| {
330 let url = manual_ws_url.read().trim().to_string();
331 if url.starts_with("ws://") || url.starts_with("wss://") {
332 ws_target.set(url.clone());
333 state.set(AppState::Connecting(url));
334 } else {
335 let mut msg_sig = status_msg.clone();
336 msg_sig.set("Enter a ws:// or wss:// URL from your desktop.".into());
337 }
338 },
339 "Connect"
340 }
341 button {
342 style: "margin-left: 0.5rem; padding: 10px 16px; background: #444; color: white; border: none; border-radius: 4px;",
343 onclick: move |_| state.set(AppState::Scanning),
344 "Try camera again"
345 }
346 }
347 },
348 AppState::Connecting(url) => rsx! {
349 div {
350 h3 { "Connecting to Desktop Engine" }
351 p { "Target: {url}" }
352 }
353 },
354 AppState::Connected | AppState::BundleReady { .. } => rsx! {
355 div {
356 style: "max-width: 480px; width: 100%;",
357 h3 { style: "color: #4CAF50;", "Companion linked" }
358 p {
359 style: "font-size: 0.9rem; color: #ccc;",
360 "Samsung Health exports are only on your phone. Select CSV files from your Samsung export, build a bundle, then share it to your desktop."
361 }
362 input {
363 id: "{file_input_id}",
364 r#type: "file",
365 accept: ".csv,text/csv",
366 multiple: true,
367 style: "margin: 1rem 0; color: #eee;",
368 }
369 div {
370 style: "display: flex; flex-wrap: wrap; gap: 0.5rem;",
371 button {
372 style: "padding: 10px 16px; background: #2a6f97; color: white; border: none; border-radius: 4px;",
373 onclick: move |_| {
374 let mut state = state.clone();
375 let mut status_msg = status_msg.clone();
376 spawn(async move {
377 match readCsvFilesFromInput(file_input_id).await {
378 Ok(js_files) => {
379 let files_val: js_sys::Array = js_files.dyn_into().unwrap_or_default();
380 let mut companion_files = Vec::new();
381 for item in files_val.iter() {
382 let obj = js_sys::Object::from(item);
383 let name = js_sys::Reflect::get(&obj, &JsValue::from_str("filename"))
384 .ok()
385 .and_then(|v| v.as_string())
386 .unwrap_or_default();
387 let content = js_sys::Reflect::get(&obj, &JsValue::from_str("csv_content"))
388 .ok()
389 .and_then(|v| v.as_string())
390 .unwrap_or_default();
391 companion_files.push(CompanionCsvFile {
392 filename: name,
393 csv_content: content,
394 });
395 }
396 match build_bundle_from_files(companion_files.clone()) {
397 Ok(json) => {
398 persistOutbox(OUTBOX_KEY, &json);
399 status_msg.set(format!(
400 "Bundle ready ({} file(s)). Saved to outbox.",
401 companion_files.len()
402 ));
403 state.set(AppState::BundleReady {
404 json: json.clone(),
405 file_count: companion_files.len(),
406 });
407 }
408 Err(e) => status_msg.set(format!("Bundle error: {e}")),
409 }
410 }
411 Err(e) => status_msg.set(format!("File read error: {e:?}")),
412 }
413 });
414 },
415 "Build health bundle"
416 }
417 if let AppState::BundleReady { json, .. } = &*state.read() {
418 button {
419 style: "padding: 10px 16px; background: #555; color: white; border: none; border-radius: 4px;",
420 onclick: {
421 let json = json.clone();
422 let status_msg = status_msg.clone();
423 let ws_handle = ws_handle.clone();
424 move |_| {
425 let json = json.clone();
426 let mut status_msg = status_msg.clone();
427 let ws_handle = ws_handle.clone();
428 spawn(async move {
429 if copyToClipboard(&json).await.is_ok() {
430 status_msg.set("Bundle copied — paste into desktop WellFair Tools.".into());
431 } else if shareBundle("WellFair Health Bundle", &json).await.is_ok() {
432 status_msg.set("Share sheet opened.".into());
433 } else {
434 status_msg.set("Copy/share unavailable — use desktop paste field.".into());
435 }
436 if let Some(ws) = ws_handle.read().clone() {
437 let payload = format!(
438 r#"{{"type":"HEALTH_BUNDLE","bundle":{json}}}"#
439 );
440 if ws.send_with_str(&payload).is_ok() {
441 status_msg.set("Bundle sent over companion link.".into());
442 }
443 }
444 });
445 }
446 },
447 "Share to desktop"
448 }
449 }
450 }
451 if !status_msg.read().is_empty() {
452 p { style: "margin-top: 0.75rem; font-size: 0.85rem; color: #aaa;", "{status_msg.read()}" }
453 }
454 }
455 },
456 AppState::Error(msg) => rsx! {
457 div {
458 h3 { style: "color: #F44336;", "Connection Error" }
459 p { "{msg}" }
460 }
461 },
462 }
463 }
464 }
465}