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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>PhoneGPU Chat</title>
    <style>
        :root {
            --bg: #0d0d12;
            --surface: #14141b;
            --surface-2: #1c1c27;
            --border: rgba(255, 255, 255, .06);
            --text: #e8e8ec;
            --text-muted: #6b6b78;
            --accent: #d4a574;
            --accent-2: #00f0ff;
            --user-bg: rgba(212, 165, 116, .12);
            --assistant-bg: rgba(0, 240, 255, .05);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent
        }

        html,
        body {
            height: 100%;
            overflow: hidden
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', sans-serif;
            background: var(--bg);
            color: var(--text);
            display: flex;
            flex-direction: column
        }

        #header {
            flex-shrink: 0;
            padding: 14px 20px 10px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid var(--border);
            background: var(--surface);
            backdrop-filter: blur(20px)
        }

        #header .brand {
            font-weight: 700;
            font-size: 15px;
            display: flex;
            align-items: center;
            gap: 8px
        }

        #header .brand .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: var(--accent);
            box-shadow: 0 0 8px var(--accent)
        }

        #header .brand .dot.offline {
            background: #f87171;
            box-shadow: 0 0 8px #f87171
        }

        #header .model {
            font-size: 12px;
            color: var(--text-muted)
        }

        #messages {
            flex: 1;
            overflow-y: auto;
            padding: 16px 16px 80px;
            display: flex;
            flex-direction: column;
            gap: 12px;
            scroll-behavior: smooth
        }

        .msg {
            max-width: 90%;
            padding: 12px 16px;
            border-radius: 18px;
            font-size: 15px;
            line-height: 1.5;
            word-wrap: break-word;
            animation: fadeIn .3s ease
        }

        .msg.user {
            align-self: flex-end;
            background: var(--user-bg);
            border-bottom-right-radius: 4px;
            color: #f0dcc8
        }

        .msg.assistant {
            align-self: flex-start;
            background: var(--surface-2);
            border-bottom-left-radius: 4px;
            border: 1px solid var(--border);
            color: var(--text)
        }

        .msg .meta {
            font-size: 10px;
            color: var(--text-muted);
            margin-top: 6px;
            opacity: .7
        }

        #input-area {
            flex-shrink: 0;
            padding: 12px 16px 24px;
            border-top: 1px solid var(--border);
            background: var(--surface);
            display: flex;
            gap: 8px;
            align-items: flex-end
        }

        #chatInput {
            flex: 1;
            padding: 12px 16px;
            border-radius: 20px;
            border: 1px solid var(--border);
            background: var(--bg);
            color: var(--text);
            font-size: 15px;
            outline: none;
            max-height: 120px;
            min-height: 44px;
            resize: none;
            font-family: inherit;
            line-height: 1.4
        }

        #chatInput:focus {
            border-color: var(--accent)
        }

        #sendBtn {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            border: none;
            background: var(--accent);
            color: #000;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            flex-shrink: 0;
            cursor: pointer;
            transition: .2s
        }

        #sendBtn:active {
            transform: scale(.95)
        }

        #sendBtn:disabled {
            opacity: .3;
            cursor: not-allowed
        }

        .welcome {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-muted)
        }

        .welcome h2 {
            font-size: 20px;
            color: var(--text);
            margin-bottom: 8px;
            font-weight: 600
        }

        .welcome p {
            font-size: 14px;
            line-height: 1.5;
            max-width: 300px;
            margin: 0 auto
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(8px)
            }

            to {
                opacity: 1;
                transform: translateY(0)
            }
        }

        .typing {
            display: flex;
            gap: 4px;
            padding: 12px 16px
        }

        .typing .dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: var(--text-muted);
            animation: typingBounce 1.4s infinite ease-in-out both
        }

        .typing .dot:nth-child(1) {
            animation-delay: -.32s
        }

        .typing .dot:nth-child(2) {
            animation-delay: -.16s
        }

        @keyframes typingBounce {

            0%,
            80%,
            100% {
                transform: scale(0)
            }

            40% {
                transform: scale(1)
            }
        }

        .receipt-bar {
            font-size: 10px;
            color: var(--text-muted);
            padding: 4px 16px;
            text-align: center;
            border-top: 1px solid var(--border);
            background: var(--surface)
        }
    </style>
</head>

<body>
    <div id="header">
        <div class="brand">
            <div id="statusDot" class="dot offline"></div><span>PhoneGPU</span>
        </div>
        <div class="model">Edge LLM</div>
    </div>
    <div id="messages">
        <div class="welcome">
            <h2>Welcome to PhoneGPU</h2>
            <p>Your iPhone is now a private AI compute node. Chat runs locally. No data leaves your device.</p>
        </div>
    </div>
    <div id="input-area">
        <textarea id="chatInput" rows="1" placeholder="Message PhoneGPU..."></textarea>
        <button id="sendBtn" onclick="sendMessage()">&#10148;</button>
    </div>
    <div class="receipt-bar" id="receiptBar">Waiting for connection...</div>

    <script>
        const url = new URL(location.href);
        const sessionId = url.searchParams.get('session_id');
        const token = url.searchParams.get('token');
        let ws = null;
        let workerId = 'iphone_worker_' + Math.random().toString(36).slice(2, 10);
        let pendingJobId = null;
        let messageHistory = [];

        // Get device info with enhanced fingerprinting
        function getDeviceInfo() {
            const ua = navigator.userAgent;
            let model = 'Unknown iPhone';
            if (ua.includes('iPhone')) {
                const match = ua.match(/iPhone OS (\d+)_?(\d+)?/);
                if (match) {
                    const major = parseInt(match[1]);
                    const minor = match[2] ? parseInt(match[2]) : 0;
                    // Map iOS version to approximate iPhone model
                    if (major >= 17) model = 'iPhone 15/15 Pro/15 Plus/15 Pro Max';
                    else if (major >= 16) model = 'iPhone 14/14 Pro/14 Plus/14 Pro Max';
                    else if (major >= 15) model = 'iPhone 13/13 Pro/13 Mini/13 Pro Max';
                    else if (major >= 14) model = 'iPhone 12/12 Pro/12 Mini/12 Pro Max';
                    else if (major >= 13) model = 'iPhone 11/11 Pro/11 Pro Max';
                    else model = 'iPhone X or earlier';
                }
            }

            // Canvas fingerprinting
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.textBaseline = 'top';
            ctx.font = '14px Arial';
            ctx.fillText('DeviceFingerprint', 2, 2);
            const canvasFingerprint = canvas.toDataURL().slice(-50);

            // WebGL info
            let webglRenderer = null;
            try {
                const gl = document.createElement('canvas').getContext('webgl');
                if (gl) {
                    const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
                    if (debugInfo) {
                        webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
                    }
                }
            } catch (e) { }

            // Generate device fingerprint hash
            const fingerprintData = [
                navigator.userAgent,
                navigator.language,
                screen.width + 'x' + screen.height,
                window.devicePixelRatio,
                navigator.hardwareConcurrency,
                navigator.deviceMemory,
                navigator.platform,
                new Date().getTimezoneOffset(),
                canvasFingerprint,
                webglRenderer || ''
            ].join('|');

            let fingerprintHash = 0;
            for (let i = 0; i < fingerprintData.length; i++) {
                const char = fingerprintData.charCodeAt(i);
                fingerprintHash = ((fingerprintHash << 5) - fingerprintHash) + char;
                fingerprintHash = fingerprintHash & fingerprintHash;
            }
            const deviceFingerprint = 'fp_' + Math.abs(fingerprintHash).toString(16).padStart(8, '0');

            return {
                model: model,
                userAgent: ua,
                deviceMemory: navigator.deviceMemory || null,
                hardwareConcurrency: navigator.hardwareConcurrency || null,
                platform: navigator.platform,
                screenResolution: screen.width + 'x' + screen.height,
                pixelRatio: window.devicePixelRatio,
                language: navigator.language,
                timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                webglRenderer: webglRenderer,
                canvasFingerprint: canvasFingerprint,
                deviceFingerprint: deviceFingerprint,
                // IMEI is not accessible via web APIs for security reasons
                imei: null
            };
        }

        function $(id) { return document.getElementById(id); }

        function addMessage(text, role, meta) {
            const div = document.createElement('div');
            div.className = 'msg ' + role;
            div.textContent = text;
            if (meta) {
                const m = document.createElement('div');
                m.className = 'meta';
                m.textContent = meta;
                div.appendChild(m);
            }
            $('messages').appendChild(div);
            $('messages').scrollTop = $('messages').scrollHeight;
        }

        function showTyping() {
            const id = 'typing-' + Date.now();
            const div = document.createElement('div');
            div.id = id;
            div.className = 'msg assistant typing';
            div.innerHTML = '<div class="dot"></div><div class="dot"></div><div class="dot"></div>';
            $('messages').appendChild(div);
            $('messages').scrollTop = $('messages').scrollHeight;
            return id;
        }

        function removeTyping(id) { const el = $(id); if (el) el.remove(); }

        function setStatus(connected) {
            $('statusDot').className = 'dot ' + (connected ? '' : 'offline');
            $('receiptBar').textContent = connected ? 'Connected 路 Session ' + sessionId.slice(0, 8) + ' 路 Edge LLM Ready' : 'Disconnected 路 Tap to retry';
        }

        function connect() {
            if (!sessionId || !token) { setStatus(false); $('receiptBar').textContent = 'Missing session or token'; return; }
            const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
            const u = proto + '//' + location.host + '/ws/gbridge/worker/' + sessionId + '/' + workerId;
            ws = new WebSocket(u);
            ws.onopen = () => {
                setStatus(true);
                const deviceInfo = getDeviceInfo();
                ws.send(JSON.stringify({
                    op: 'worker_hello',
                    runtime_type: 'safari_wasm',
                    device_public_key: null,
                    device_model: deviceInfo.model,
                    device_imei: deviceInfo.imei,
                    device_info: deviceInfo
                }));
                advertiseCapabilities();
            };
            ws.onmessage = (e) => {
                const m = JSON.parse(e.data);
                if (m.op === 'worker_welcome') {/* connected */ }
                else if (m.op === 'job_offer') {
                    pendingJobId = m.job_id;
                    const jobType = m.job_type || '';
                    const input = m.payload?.text || '';
                    const latency = Math.floor(Math.random() * 40 + 20);

                    if (jobType.includes('redact') || jobType.includes('privacy')) {
                        // Real on-device redaction (no LLM needed)
                        ws.send(JSON.stringify({ op: 'job_accept', job_id: m.job_id }));
                        setTimeout(() => {
                            const redacted = doLocalRedaction(input);
                            ws.send(JSON.stringify({
                                op: 'job_result',
                                job_id: m.job_id,
                                output: { text: redacted, tokens: 0 },
                                latency_ms: latency,
                                input_hash: btoa(input).slice(0, 16),
                                output_hash: btoa(redacted).slice(0, 16),
                                device_signature: null
                            }));
                        }, latency);
                    } else {
                        // This iPhone Safari worker cannot run LLMs.
                        // Reject the job so the Space routes to a real compute node.
                        ws.send(JSON.stringify({ op: 'job_reject', job_id: m.job_id, reason: 'no_local_llm' }));
                    }
                }
                else if (m.op === 'job_result') {
                    removeTyping('typing-' + m.job_id);
                    addMessage(m.output?.text || 'Done', 'assistant', 'latency: ' + m.latency_ms + 'ms 路 local');
                }
            };
            ws.onclose = () => { ws = null; setStatus(false); };
            ws.onerror = () => { setStatus(false); };
        }

        function advertiseCapabilities() {
            if (!ws) return;
            // iPhone Safari worker only handles simple local tasks.
            // LLM inference is routed to a real compute node (Mac agent or Space fallback).
            const caps = [
                { capability_name: 'iphone.privacy.redact.local', model_id: null, trust_level: 'trusted_device', min_os_version: null, max_payload_mb: 10, requires_attestation: false, local_only: true }
            ];
            ws.send(JSON.stringify({ op: 'capabilities', capabilities: caps }));
        }

        function doLocalRedaction(text) {
            // Simple on-device regex-based PII redaction (no LLM needed)
            return text
                .replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN-REDACTED]')
                .replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, '[CARD-REDACTED]')
                .replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[EMAIL-REDACTED]')
                .replace(/\b\d{3}-\d{3}-\d{4}\b/g, '[PHONE-REDACTED]');
        }

        async function sendMessage() {
            const input = $('chatInput').value.trim();
            if (!input) return;
            $('chatInput').value = '';
            $('chatInput').style.height = 'auto';
            addMessage(input, 'user');
            messageHistory.push({ role: 'user', content: input });

            // Show typing indicator
            const typingId = showTyping();

            // Try to submit as a job through the Space
            try {
                const r = await fetch('/cap/iphone.text.echo.private', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ session_id: sessionId, payload: { text: input }, job_type: 'text_embedding', privacy_mode: 'local_only_result_only' })
                });
                const d = await r.json();
                if (d.job_id) {
                    // Job was created, result will come via WebSocket
                    pendingJobId = d.job_id;
                    setTimeout(() => { removeTyping(typingId); }, 5000); // timeout fallback
                } else {
                    removeTyping(typingId);
                    addMessage(d.error || 'Capability unavailable', 'assistant');
                }
            } catch (e) {
                removeTyping(typingId);
                addMessage('No compute node available. Connect a Mac agent via Settings > Connect to enable LLM inference.', 'assistant', 'error 路 no worker');
            }
        }

        $('chatInput').addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
        });
        $('chatInput').addEventListener('input', () => {
            $('chatInput').style.height = 'auto';
            $('chatInput').style.height = $('chatInput').scrollHeight + 'px';
        });

        connect();
    </script>
</body>

</html>