qualia_cooperative_core/qapp_package/
remote_controller.rs1use super::pwa::{PwaBundle, PwaContent, PwaFile};
11
12const CACHE: &str = "webizen-remote-controller-v1";
13
14pub fn generate_remote_controller_pwa() -> PwaBundle {
16 PwaBundle {
17 files: vec![
18 PwaFile {
19 path: "index.html".into(),
20 content: PwaContent::Text(index_html()),
21 },
22 PwaFile {
23 path: "manifest.webmanifest".into(),
24 content: PwaContent::Text(webmanifest()),
25 },
26 PwaFile {
27 path: "sw.js".into(),
28 content: PwaContent::Text(service_worker()),
29 },
30 PwaFile {
31 path: "app.js".into(),
32 content: PwaContent::Text(app_js()),
33 },
34 PwaFile {
35 path: "icon.svg".into(),
36 content: PwaContent::Text(icon_svg()),
37 },
38 ],
39 }
40}
41
42fn webmanifest() -> String {
43 r###"{
44 "id": "webizen.remote-controller",
45 "name": "Webizen Remote",
46 "short_name": "Webizen",
47 "description": "Phone Surface Controller for Qualia mindware — local apparatus, not cloud.",
48 "start_url": "./",
49 "scope": "./",
50 "display": "standalone",
51 "orientation": "portrait-primary",
52 "theme_color": "#0b1220",
53 "background_color": "#0b1220",
54 "icons": [
55 {
56 "src": "icon.svg",
57 "sizes": "any",
58 "type": "image/svg+xml",
59 "purpose": "any maskable"
60 }
61 ]
62}"###
63 .into()
64}
65
66fn service_worker() -> String {
67 format!(
68 r###"const CACHE = '{CACHE}';
69const PRECACHE = ['./', './index.html', './app.js', './manifest.webmanifest', './icon.svg'];
70self.addEventListener('install', (e) => {{
71 e.waitUntil(caches.open(CACHE).then((c) => c.addAll(PRECACHE)).then(() => self.skipWaiting()));
72}});
73self.addEventListener('activate', (e) => {{
74 e.waitUntil(
75 caches.keys().then((keys) =>
76 Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
77 ).then(() => self.clients.claim())
78 );
79}});
80self.addEventListener('fetch', (e) => {{
81 if (e.request.method !== 'GET') return;
82 const url = new URL(e.request.url);
83 if (url.pathname.includes('/api/')) return;
84 e.respondWith(
85 caches.match(e.request).then((cached) => {{
86 if (cached) return cached;
87 return fetch(e.request).then((res) => {{
88 if (res && res.ok && res.type === 'basic') {{
89 const copy = res.clone();
90 caches.open(CACHE).then((c) => c.put(e.request, copy));
91 }}
92 return res;
93 }});
94 }})
95 );
96}});
97"###
98 )
99}
100
101fn icon_svg() -> String {
102 r###"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
103 <rect width="128" height="128" rx="28" fill="#0b1220"/>
104 <circle cx="64" cy="64" r="36" fill="none" stroke="#8b5cf6" stroke-width="6"/>
105 <circle cx="64" cy="64" r="12" fill="#a78bfa"/>
106</svg>"###
107 .into()
108}
109
110fn index_html() -> String {
111 r###"<!DOCTYPE html>
112<html lang="en">
113<head>
114 <meta charset="utf-8" />
115 <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
116 <meta name="theme-color" content="#0b1220" />
117 <meta name="apple-mobile-web-app-capable" content="yes" />
118 <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
119 <link rel="manifest" href="manifest.webmanifest" />
120 <link rel="icon" href="icon.svg" type="image/svg+xml" />
121 <title>Webizen Remote</title>
122 <style>
123 :root {
124 --bg: #0b1220; --panel: #111827; --border: #334155; --text: #e2e8f0;
125 --muted: #94a3b8; --accent: #8b5cf6; --ok: #34d399; --warn: #fbbf24;
126 }
127 * { box-sizing: border-box; }
128 body {
129 margin: 0; min-height: 100dvh; font: 15px/1.45 system-ui, sans-serif;
130 background: var(--bg); color: var(--text);
131 padding: max(0.75rem, env(safe-area-inset-top)) 0.85rem max(1rem, env(safe-area-inset-bottom));
132 }
133 h1 { font-size: 1.15rem; margin: 0 0 0.25rem; color: #e9d5ff; }
134 .sub { color: var(--muted); font-size: 0.78rem; margin: 0 0 1rem; line-height: 1.4; }
135 .chip {
136 display: inline-flex; align-items: center; gap: 0.35rem;
137 font-size: 0.65rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em;
138 padding: 0.2rem 0.5rem; border-radius: 999px; border: 1px solid var(--border); color: var(--muted);
139 }
140 .chip.ok { color: var(--ok); border-color: #065f46; }
141 .chip.warn { color: var(--warn); border-color: #92400e; }
142 .card {
143 background: var(--panel); border: 1px solid var(--border); border-radius: 14px;
144 padding: 0.85rem; margin-bottom: 0.75rem;
145 }
146 label { display: block; font-size: 0.68rem; color: var(--muted); font-weight: 600; margin: 0 0 0.25rem; }
147 select, button, input {
148 width: 100%; font: inherit; border-radius: 10px; border: 1px solid var(--border);
149 background: #0b1220; color: var(--text); padding: 0.55rem 0.65rem; margin-bottom: 0.5rem;
150 }
151 button {
152 background: var(--accent); border-color: #6d28d9; font-weight: 700; cursor: pointer;
153 }
154 button.secondary { background: #1e293b; border-color: var(--border); font-weight: 600; }
155 button.row { width: auto; flex: 1; }
156 .row { display: flex; gap: 0.4rem; flex-wrap: wrap; }
157 .mono { font-family: ui-monospace, monospace; font-size: 0.72rem; color: #c4b5fd; word-break: break-all; }
158 .status { font-size: 0.75rem; color: var(--muted); min-height: 1.2em; }
159 .err { color: #fca5a5; }
160 </style>
161</head>
162<body>
163 <h1>Webizen Remote</h1>
164 <p class="sub">Surface Controller for your local Qualia apparatus. Install to home screen when served from a secure origin (localhost or HTTPS). Not a cloud product.</p>
165 <div style="display:flex;gap:0.35rem;flex-wrap:wrap;margin-bottom:0.75rem;">
166 <span class="chip" id="host-chip">host: …</span>
167 <span class="chip" id="honesty-chip">Partial · controller shell</span>
168 </div>
169
170 <div class="card">
171 <label>Observer</label>
172 <select id="observer">
173 <option value="principal">Principal</option>
174 <option value="peer">Peer</option>
175 <option value="public">Public</option>
176 <option value="instrument">Instrument</option>
177 <option value="guardian">Guardian</option>
178 <option value="steward">Steward</option>
179 <option value="auditor">Auditor</option>
180 </select>
181 <label>Morph</label>
182 <div class="row">
183 <button type="button" class="secondary row" id="btn-flat">Flatten</button>
184 <button type="button" class="secondary row" id="btn-spatial">Spatialize</button>
185 <button type="button" class="secondary row" id="btn-both">Both</button>
186 </div>
187 <button type="button" id="btn-sync">Sync session</button>
188 </div>
189
190 <div class="card">
191 <label>Shared selection</label>
192 <div class="mono" id="selection">—</div>
193 <label style="margin-top:0.5rem;">Attention URL</label>
194 <div class="mono" id="attention">—</div>
195 </div>
196
197 <div class="card">
198 <label>Select by URI (Memory / page)</label>
199 <input id="uri" type="url" placeholder="https://… or urn:…" inputmode="url" />
200 <button type="button" id="btn-select">Select entity</button>
201 </div>
202
203 <div class="card">
204 <label>Sensors (web APIs · opt-in)</label>
205 <div class="row">
206 <button type="button" class="secondary row" id="btn-orient">Read orientation</button>
207 <button type="button" class="secondary row" id="btn-geo">Read place</button>
208 </div>
209 <div class="mono" id="sensor-out">Off until you tap. Sanctuary: leave off.</div>
210 </div>
211
212 <p class="status" id="status"></p>
213 <script src="app.js"></script>
214</body>
215</html>"###
216 .into()
217}
218
219fn app_js() -> String {
220 r###"
221(function () {
222 'use strict';
223 if ('serviceWorker' in navigator) {
224 window.addEventListener('load', function () {
225 navigator.serviceWorker.register('./sw.js').catch(function () {});
226 });
227 }
228
229 var statusEl = document.getElementById('status');
230 var hostChip = document.getElementById('host-chip');
231 var honesty = document.getElementById('honesty-chip');
232
233 function setStatus(msg, isErr) {
234 statusEl.textContent = msg || '';
235 statusEl.className = 'status' + (isErr ? ' err' : '');
236 }
237
238 function apiBase() {
239 // Same origin when served under /remote-controller/
240 return '';
241 }
242
243 async function api(path, opts) {
244 var res = await fetch(apiBase() + path, opts || {});
245 if (!res.ok) {
246 var t = await res.text();
247 throw new Error(t || res.statusText);
248 }
249 return res.json();
250 }
251
252 function renderSession(s) {
253 var sel = (s.selection && s.selection[0]) || null;
254 var id = typeof sel === 'number' ? sel : (sel && (sel['0'] || sel));
255 document.getElementById('selection').textContent = id ? String(id) : '—';
256 document.getElementById('attention').textContent = s.attention_url || '—';
257 if (s.observer) document.getElementById('observer').value = s.observer;
258 hostChip.textContent = 'host: paired';
259 hostChip.className = 'chip ok';
260 honesty.textContent = 'Partial · installable controller';
261 honesty.className = 'chip warn';
262 }
263
264 async function sync() {
265 setStatus('Syncing…');
266 try {
267 var s = await api('/api/view/session');
268 renderSession(s);
269 setStatus('Session synced');
270 } catch (e) {
271 hostChip.textContent = 'host: offline';
272 hostChip.className = 'chip warn';
273 setStatus('Host unreachable — open this PWA from the desktop control plane URL. ' + e.message, true);
274 }
275 }
276
277 document.getElementById('btn-sync').onclick = sync;
278 document.getElementById('observer').onchange = async function () {
279 var v = document.getElementById('observer').value;
280 try {
281 var s = await api('/api/view/set_observer', {
282 method: 'POST',
283 headers: { 'Content-Type': 'application/json' },
284 body: JSON.stringify({ status: v }),
285 });
286 renderSession(s);
287 setStatus('Observer → ' + v);
288 } catch (e) {
289 setStatus(String(e.message || e), true);
290 }
291 };
292
293 function morph(mode) {
294 return async function () {
295 try {
296 await api('/api/view/morph', {
297 method: 'POST',
298 headers: { 'Content-Type': 'application/json' },
299 body: JSON.stringify({ mode: mode }),
300 });
301 setStatus('Morph → ' + mode + ' (desktop habitat)');
302 await sync();
303 } catch (e) {
304 setStatus(String(e.message || e), true);
305 }
306 };
307 }
308 document.getElementById('btn-flat').onclick = morph('flatten');
309 document.getElementById('btn-spatial').onclick = morph('spatialize');
310 document.getElementById('btn-both').onclick = morph('both');
311
312 document.getElementById('btn-select').onclick = async function () {
313 var uri = (document.getElementById('uri').value || '').trim();
314 if (!uri) {
315 setStatus('Enter a URI', true);
316 return;
317 }
318 try {
319 var s = await api('/api/view/select_uri', {
320 method: 'POST',
321 headers: { 'Content-Type': 'application/json' },
322 body: JSON.stringify({ uri: uri }),
323 });
324 renderSession(s);
325 setStatus('Selected ' + uri);
326 } catch (e) {
327 setStatus(String(e.message || e), true);
328 }
329 };
330
331 document.getElementById('btn-orient').onclick = async function () {
332 var out = document.getElementById('sensor-out');
333 if (!window.DeviceOrientationEvent) {
334 out.textContent = 'Orientation API unavailable (honesty: Partial)';
335 return;
336 }
337 function once(e) {
338 out.textContent =
339 'alpha=' + (e.alpha != null ? e.alpha.toFixed(1) : '—') +
340 ' beta=' + (e.beta != null ? e.beta.toFixed(1) : '—') +
341 ' gamma=' + (e.gamma != null ? e.gamma.toFixed(1) : '—');
342 window.removeEventListener('deviceorientation', once);
343 }
344 if (typeof DeviceOrientationEvent.requestPermission === 'function') {
345 try {
346 var p = await DeviceOrientationEvent.requestPermission();
347 if (p !== 'granted') {
348 out.textContent = 'Permission denied';
349 return;
350 }
351 } catch (err) {
352 out.textContent = 'Permission error';
353 return;
354 }
355 }
356 window.addEventListener('deviceorientation', once);
357 out.textContent = 'Listening for one sample…';
358 };
359
360 document.getElementById('btn-geo').onclick = function () {
361 var out = document.getElementById('sensor-out');
362 if (!navigator.geolocation) {
363 out.textContent = 'Geolocation unavailable (honesty: Partial)';
364 return;
365 }
366 navigator.geolocation.getCurrentPosition(
367 function (pos) {
368 out.textContent =
369 pos.coords.latitude.toFixed(5) + ', ' + pos.coords.longitude.toFixed(5);
370 },
371 function () {
372 out.textContent = 'Place denied or unavailable';
373 },
374 { enableHighAccuracy: false, maximumAge: 60000, timeout: 10000 }
375 );
376 };
377
378 sync();
379})();
380"###
381 .into()
382}
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387
388 #[test]
389 fn remote_controller_bundle_has_install_shell() {
390 let b = generate_remote_controller_pwa();
391 assert!(b.get("index.html").is_some());
392 assert!(b.get("manifest.webmanifest").is_some());
393 assert!(b.get("sw.js").is_some());
394 assert!(b.get("app.js").is_some());
395 let html = b.text_of("index.html").unwrap();
396 assert!(html.contains("Webizen Remote"));
397 assert!(html.contains("manifest.webmanifest"));
398 let mf = b.text_of("manifest.webmanifest").unwrap();
399 assert!(mf.contains("standalone"));
400 let app = b.text_of("app.js").unwrap();
401 assert!(app.contains("/api/view/session"));
402 }
403}