File size: 7,401 Bytes
d958e80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
let socket = null;
let sessionId = null;
let workerId = null;
let token = null;
let heartbeatInterval = null;
let deviceKeys = null;

function log(msg) {
  const el = document.getElementById('log');
  const line = document.createElement('div');
  line.textContent = new Date().toLocaleTimeString() + ' ' + msg;
  el.appendChild(line);
  el.scrollTop = el.scrollHeight;
  console.log(msg);
}

function parseSessionFromUrl() {
  const params = new URLSearchParams(window.location.search);
  sessionId = params.get('session_id');
  token = params.get('token');
  return { sessionId, token };
}

async function connectToSpace() {
  parseSessionFromUrl();
  if (!sessionId || !token) {
    log('No session_id or token in URL');
    return;
  }

  workerId = 'wk_' + Math.random().toString(36).slice(2, 10);
  log('Connecting as ' + workerId + ' to session ' + sessionId);

  const wsUrl = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws/worker/' + sessionId + '/' + workerId;
  socket = new WebSocket(wsUrl);

  socket.onopen = async () => {
    log('WebSocket connected');
    updateStatus('connecting');
    deviceKeys = await ReceiptCrypto.loadDeviceKeypair();
    const runtime = PhoneRuntime.selectBestRuntime();
    sendWorkerHello(runtime);
  };

  socket.onmessage = (event) => {
    const msg = JSON.parse(event.data);
    handleSocketMessage(msg);
  };

  socket.onclose = () => {
    log('WebSocket closed');
    updateStatus('offline');
    stopHeartbeat();
  };

  socket.onerror = (err) => {
    log('WebSocket error');
    updateStatus('offline');
  };

  document.getElementById('btnConnect').disabled = true;
  document.getElementById('btnDisconnect').disabled = false;
}

function sendWorkerHello(runtimeType) {
  if (!socket) return;
  socket.send(JSON.stringify({
    op: 'worker_hello',
    worker_id: workerId,
    runtime_type: runtimeType,
    device_public_key: deviceKeys ? deviceKeys.publicKey : null,
  }));
}

function detectDeviceInfo() {
  const battery = navigator.getBattery ? navigator.getBattery() : Promise.resolve({});
  battery.then(b => {
    document.getElementById('batteryValue').textContent = (b.level ? Math.round(b.level * 100) + '%' : 'unknown');
  }).catch(() => {});
  document.getElementById('networkValue').textContent = navigator.connection ? navigator.connection.effectiveType : 'unknown';
  document.getElementById('thermalValue').textContent = 'nominal'; // iOS Web API limitation
  document.getElementById('runtimeValue').textContent = PhoneRuntime.selectBestRuntime();
}

function advertiseCapabilities() {
  if (!socket) return;
  const caps = [
    { capability_name: 'iphone.text.embedding.private', runtime_type: PhoneRuntime.selectBestRuntime(), model_id: 'mock-embedding' },
    { capability_name: 'iphone.image.classify.local', runtime_type: PhoneRuntime.selectBestRuntime(), model_id: 'mock-image' },
    { capability_name: 'iphone.privacy.redact.local', runtime_type: PhoneRuntime.selectBestRuntime(), model_id: 'mock-redact' },
  ];
  socket.send(JSON.stringify({ op: 'capabilities', worker_id: workerId, capabilities: caps }));
  renderCapabilities(caps);
  log('Capabilities advertised');
}

function handleSocketMessage(msg) {
  switch (msg.op) {
    case 'worker_welcome':
      updateStatus('online');
      detectDeviceInfo();
      advertiseCapabilities();
      startHeartbeat();
      break;
    case 'job_offer':
      handleJobOffer(msg);
      break;
    case 'session_update':
      log('Session update: ' + JSON.stringify(msg));
      break;
    case 'error':
      log('Server error: ' + msg.error);
      break;
  }
}

async function handleJobOffer(job) {
  log('Job offered: ' + job.job_type + ' (' + job.job_id + ')');

  // Auto-accept for v1
  socket.send(JSON.stringify({ op: 'job_accept', job_id: job.job_id, worker_id: workerId }));

  const startTime = Date.now();
  let output = {};

  try {
    switch (job.job_type) {
      case 'text_embedding':
        output = await PhoneRuntime.runTextEmbedding(job.payload.text || '');
        break;
      case 'image_classification':
        output = await PhoneRuntime.runImageClassification(job.payload.image || '');
        break;
      case 'privacy_redaction':
        output = await PhoneRuntime.runPrivacyRedaction(job.payload.text || '');
        break;
      default:
        throw new Error('Unsupported job type: ' + job.job_type);
    }
  } catch (err) {
    log('Job failed: ' + err.message);
    socket.send(JSON.stringify({ op: 'job_result', job_id: job.job_id, worker_id: workerId, output: { error: err.message }, latency_ms: Date.now() - startTime }));
    return;
  }

  const latencyMs = Date.now() - startTime;
  const inputHash = await ReceiptCrypto.makeInputHash(job.payload);
  const outputHash = await ReceiptCrypto.makeOutputHash(output);
  const deviceSignature = await ReceiptCrypto.signReceipt({
    job_id: job.job_id,
    worker_id: workerId,
    input_hash: inputHash,
    output_hash: outputHash,
    latency_ms: latencyMs,
  });

  socket.send(JSON.stringify({
    op: 'job_result',
    job_id: job.job_id,
    worker_id: workerId,
    output: output,
    latency_ms: latencyMs,
    input_hash: inputHash,
    output_hash: outputHash,
    device_signature: deviceSignature,
  }));

  addReceiptCard(job.job_id, job.job_type, latencyMs, outputHash);
  log('Job completed: ' + job.job_id + ' in ' + latencyMs + 'ms');
}

function startHeartbeat() {
  heartbeatInterval = setInterval(() => {
    if (!socket || socket.readyState !== WebSocket.OPEN) return;
    socket.send(JSON.stringify({
      op: 'heartbeat',
      worker_id: workerId,
      battery_level: 0.8, // mock for v1
      thermal_state: 'nominal',
      jobs_completed: document.querySelectorAll('.receipt-card').length,
    }));
  }, 5000);
}

function stopHeartbeat() {
  if (heartbeatInterval) clearInterval(heartbeatInterval);
  heartbeatInterval = null;
}

function disconnectWorker() {
  stopHeartbeat();
  if (socket) {
    socket.send(JSON.stringify({ op: 'disconnect', worker_id: workerId, reason: 'user' }));
    socket.close();
    socket = null;
  }
  updateStatus('offline');
  document.getElementById('btnConnect').disabled = false;
  document.getElementById('btnDisconnect').disabled = true;
}

function updateStatus(status) {
  const badge = document.getElementById('statusBadge');
  badge.className = 'status-badge status-' + status;
  badge.textContent = status.charAt(0).toUpperCase() + status.slice(1);
}

function renderCapabilities(caps) {
  const el = document.getElementById('capabilitiesList');
  el.innerHTML = caps.map(c =>
    '<div class="job-card"><div class="job-type">' + c.capability_name + '</div><div style="font-size:12px;color:#64748b">' + c.runtime_type + ' / ' + c.model_id + '</div></div>'
  ).join('');
}

function addReceiptCard(jobId, jobType, latencyMs, outputHash) {
  const el = document.getElementById('receiptLog');
  const card = document.createElement('div');
  card.className = 'receipt-card';
  card.innerHTML = '<div style="font-weight:700;margin-bottom:4px;">' + jobType + '</div><div>Latency: ' + latencyMs + 'ms</div><div style="color:#059669">' + outputHash.slice(0, 24) + '...</div>';
  el.prepend(card);
}

// Auto-connect if URL has session params
if (window.location.search.includes('session_id')) {
  window.addEventListener('load', () => {
    setTimeout(connectToSpace, 500);
  });
}