c64-ready 0.11.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +10 -2
  2. package/dist/assets/CHANGELOG-B12WeYEc.js +116 -0
  3. package/dist/assets/index-fUdEY2R7.js +610 -0
  4. package/dist/index.html +1 -1
  5. package/dist/tools/anykey-c64.prg +0 -0
  6. package/dist/tools/tools.json +6 -0
  7. package/dist-ts/emulator/c64-emulator.d.ts +3 -0
  8. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  9. package/dist-ts/emulator/c64-emulator.js +36 -4
  10. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  11. package/dist-ts/emulator/crt-info.d.ts +61 -0
  12. package/dist-ts/emulator/crt-info.d.ts.map +1 -0
  13. package/dist-ts/emulator/crt-info.js +190 -0
  14. package/dist-ts/emulator/crt-info.js.map +1 -0
  15. package/dist-ts/emulator/input.d.ts +96 -0
  16. package/dist-ts/emulator/input.d.ts.map +1 -1
  17. package/dist-ts/emulator/input.js +549 -4
  18. package/dist-ts/emulator/input.js.map +1 -1
  19. package/dist-ts/headless/c64-headless.d.ts +1 -0
  20. package/dist-ts/headless/c64-headless.d.ts.map +1 -1
  21. package/dist-ts/headless/c64-headless.js +5 -0
  22. package/dist-ts/headless/c64-headless.js.map +1 -1
  23. package/dist-ts/types/emulator.d.ts +2 -1
  24. package/dist-ts/types/emulator.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/src/emulator/c64-emulator.ts +34 -2
  27. package/src/emulator/crt-info.ts +35 -23
  28. package/src/emulator/input.ts +5 -2
  29. package/src/headless/c64-headless.ts +5 -0
  30. package/src/headless/c64-key-map.mjs +1 -1
  31. package/src/headless/headless-cli.mjs +410 -232
  32. package/src/headless/input-server.mjs +463 -198
  33. package/src/headless/webrtc-server.mjs +235 -70
  34. package/src/main.ts +37 -3
  35. package/src/player/c64-player.ts +121 -37
  36. package/src/player/styles/ui-controller.css +114 -21
  37. package/src/player/ui-controller.ts +176 -8
  38. package/dist/assets/CHANGELOG-CPMeNyjb.js +0 -261
  39. package/dist/assets/index-CeQto0sd.js +0 -499
@@ -17,11 +17,13 @@ import { randomBytes } from 'crypto';
17
17
  * @param {number} [opts.port=9001]
18
18
  * @param {Function} opts.onInput
19
19
  * @param {Function} [opts.onCommand] Called with emulator commands from the host:
20
- * { type: 'load-crt'|'detach-crt'|'hard-reset', ... }
20
+ * { type: 'load-crt'|'detach-crt'|'hard-reset'|'reboot', ... }
21
21
  * @param {boolean} [opts.verbose]
22
22
  * @param {number} [opts.hostTimeoutMs=300000]
23
23
  * @param {Function} [opts.validateKickToken]
24
24
  * @param {Function} [opts.validateAdminToken]
25
+ * @param {number} [opts.hostReconnectGraceMs=8000]
26
+ * @param {number} [opts.p2ReconnectGraceMs=5000]
25
27
  * @param {Function} [opts.getRuntimeStats]
26
28
  * @param {Function} [opts.getWebrtcPeerSnapshot]
27
29
  * @param {Function} [opts.disconnectWebrtcPeersByAddr]
@@ -31,17 +33,17 @@ import { randomBytes } from 'crypto';
31
33
  * @returns {{ wss: WebSocketServer, close: () => Promise<void> }}
32
34
  */
33
35
  export function createInputServer(opts = {}) {
34
- const port = opts.port ?? 9001;
35
- const onInput = opts.onInput;
36
- const onCommand = opts.onCommand ?? (() => {});
37
- const verbose = opts.verbose ?? false;
38
- const logEvents = opts.logEvents ?? false;
39
- const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
36
+ const port = opts.port ?? 9001;
37
+ const onInput = opts.onInput;
38
+ const onCommand = opts.onCommand ?? (() => {});
39
+ const verbose = opts.verbose ?? false;
40
+ const logEvents = opts.logEvents ?? false;
41
+ const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
40
42
  const validateKickToken = opts.validateKickToken ?? (() => null);
41
43
  const validateAdminToken = opts.validateAdminToken ?? (() => false);
42
- const serverVersion = opts.serverVersion ?? null;
43
- const serverGitHash = opts.serverGitHash ?? null;
44
- const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
44
+ const serverVersion = opts.serverVersion ?? null;
45
+ const serverGitHash = opts.serverGitHash ?? null;
46
+ const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
45
47
  const getWebrtcPeerSnapshot = opts.getWebrtcPeerSnapshot ?? (() => null);
46
48
  const disconnectWebrtcPeersByAddr = opts.disconnectWebrtcPeersByAddr ?? (() => 0);
47
49
  const disconnectAllWebrtcPeers = opts.disconnectAllWebrtcPeers ?? (() => 0);
@@ -49,7 +51,7 @@ export function createInputServer(opts = {}) {
49
51
  // ── Input flood instrumentation ───────────────────────────────────────────────
50
52
  const _inputStats = {
51
53
  host: { joystick: 0, key: 0, lastMsgTime: 0 },
52
- p2: { joystick: 0, key: 0, lastMsgTime: 0 },
54
+ p2: { joystick: 0, key: 0, lastMsgTime: 0 },
53
55
  };
54
56
  // ── Input latency tracking ─────────────────────────────────────────────────
55
57
  const LATENCY_SPIKE_MS = 200;
@@ -60,7 +62,7 @@ export function createInputServer(opts = {}) {
60
62
  let _networkStatsTimer = null;
61
63
  const _networkStats = {
62
64
  host: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
63
- p2: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
65
+ p2: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
64
66
  };
65
67
 
66
68
  function broadcastNetworkStats() {
@@ -70,14 +72,18 @@ export function createInputServer(opts = {}) {
70
72
  type: 'network-stats',
71
73
  serverTime: Date.now(),
72
74
  host: { ..._networkStats.host },
73
- p2: { ..._networkStats.p2 },
75
+ p2: { ..._networkStats.p2 },
74
76
  ...(runtime ? { server: runtime } : {}),
75
77
  });
76
78
  if (hostClient && hostClient.readyState === hostClient.OPEN) {
77
- try { hostClient.send(payload); } catch (_) {}
79
+ try {
80
+ hostClient.send(payload);
81
+ } catch (_) {}
78
82
  }
79
83
  if (p2Client && p2Client.readyState === p2Client.OPEN) {
80
- try { p2Client.send(payload); } catch (_) {}
84
+ try {
85
+ p2Client.send(payload);
86
+ } catch (_) {}
81
87
  }
82
88
  }
83
89
  const INPUT_LOG_INTERVAL_MS = 5000; // every 5 seconds
@@ -87,10 +93,12 @@ export function createInputServer(opts = {}) {
87
93
  _inputLogTimer = setInterval(() => {
88
94
  const now = Date.now();
89
95
  // Only log if there's been recent activity (within last 10s)
90
- const h = _inputStats.host.lastMsgTime && (now - _inputStats.host.lastMsgTime < 10000);
91
- const p = _inputStats.p2.lastMsgTime && (now - _inputStats.p2.lastMsgTime < 10000);
96
+ const h = _inputStats.host.lastMsgTime && now - _inputStats.host.lastMsgTime < 10000;
97
+ const p = _inputStats.p2.lastMsgTime && now - _inputStats.p2.lastMsgTime < 10000;
92
98
  if ((h || p) && (logEvents || verbose)) {
93
- console.error(`[event] input-flood host-joystick=${_inputStats.host.joystick} host-key=${_inputStats.host.key} p2-joystick=${_inputStats.p2.joystick} p2-key=${_inputStats.p2.key}`);
99
+ console.error(
100
+ `[event] input-flood host-joystick=${_inputStats.host.joystick} host-key=${_inputStats.host.key} p2-joystick=${_inputStats.p2.joystick} p2-key=${_inputStats.p2.key}`,
101
+ );
94
102
  }
95
103
  // Reset counters after reporting
96
104
  _inputStats.host.joystick = 0;
@@ -113,23 +121,26 @@ export function createInputServer(opts = {}) {
113
121
  function logEv(tag, fields = {}) {
114
122
  if (!logEvents) return;
115
123
  const ts = new Date().toISOString();
116
- const pairs = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
124
+ const pairs = Object.entries(fields)
125
+ .map(([k, v]) => `${k}=${v}`)
126
+ .join(' ');
117
127
  console.error(`[event] ${ts} ${tag}${pairs ? ' ' + pairs : ''}`);
118
128
  }
119
129
 
120
130
  const wss = new WebSocketServer({ port });
121
131
  const HOST_RECONNECT_GRACE = opts.hostReconnectGraceMs ?? 8_000;
132
+ const P2_RECONNECT_GRACE = opts.p2ReconnectGraceMs ?? HOST_RECONNECT_GRACE;
122
133
 
123
134
  // ── Room state ────────────────────────────────────────────────────────────
124
- let hostClient = null;
125
- let hostUsername = null;
135
+ let hostClient = null;
136
+ let hostUsername = null;
126
137
 
127
- let p2Client = null;
128
- let p2Username = null;
129
- let inviteToken = null;
138
+ let p2Client = null;
139
+ let p2Username = null;
140
+ let inviteToken = null;
130
141
 
131
142
  // Joystick port swap — when true, host uses port 1, P2 uses port 2
132
- let portsSwapped = false;
143
+ let portsSwapped = false;
133
144
  // Optional host-defined override for independent per-role joystick ports.
134
145
  let portOverrideEnabled = false;
135
146
  let overrideHostPort = 2;
@@ -138,17 +149,19 @@ export function createInputServer(opts = {}) {
138
149
  // ── Host reconnect grace period ───────────────────────────────────────────
139
150
  // When the host disconnects we hold off on promoting P2 for up to
140
151
  // HOST_RECONNECT_GRACE ms, giving the host a chance to refresh and reclaim.
141
- let graceTimer = null;
142
- let pendingHostUsername = null; // username of the disconnected host
152
+ let graceTimer = null;
153
+ let pendingHostUsername = null; // username of the disconnected host
154
+ let p2GraceTimer = null;
155
+ let pendingP2Username = null;
143
156
  // Currently loaded cartridge filename (for hello message to late joiners).
144
157
  // Seeded from opts.initialCartFilename when a default game is pre-loaded.
145
158
  let currentCartFilename = opts.initialCartFilename ?? null;
146
159
 
147
160
  function hostPort() {
148
- return portOverrideEnabled ? overrideHostPort : (portsSwapped ? 1 : 2);
161
+ return portOverrideEnabled ? overrideHostPort : portsSwapped ? 1 : 2;
149
162
  }
150
163
  function p2Port() {
151
- return portOverrideEnabled ? overrideP2Port : (portsSwapped ? 2 : 1);
164
+ return portOverrideEnabled ? overrideP2Port : portsSwapped ? 2 : 1;
152
165
  }
153
166
 
154
167
  // ── Host inactivity timeout ───────────────────────────────────────────────
@@ -161,7 +174,10 @@ export function createInputServer(opts = {}) {
161
174
  }
162
175
 
163
176
  function clearHostTimeout() {
164
- if (hostTimeoutTimer) { clearTimeout(hostTimeoutTimer); hostTimeoutTimer = null; }
177
+ if (hostTimeoutTimer) {
178
+ clearTimeout(hostTimeoutTimer);
179
+ hostTimeoutTimer = null;
180
+ }
165
181
  }
166
182
 
167
183
  // ── P2 inactivity timeout ─────────────────────────────────────────────────
@@ -174,7 +190,10 @@ export function createInputServer(opts = {}) {
174
190
  }
175
191
 
176
192
  function clearP2Timeout() {
177
- if (p2TimeoutTimer) { clearTimeout(p2TimeoutTimer); p2TimeoutTimer = null; }
193
+ if (p2TimeoutTimer) {
194
+ clearTimeout(p2TimeoutTimer);
195
+ p2TimeoutTimer = null;
196
+ }
178
197
  }
179
198
 
180
199
  function kickP2ForInactivity() {
@@ -186,8 +205,9 @@ export function createInputServer(opts = {}) {
186
205
  }
187
206
  const leaving = p2Username;
188
207
  setWsIdentity(p2Client, 'spectator', null);
189
- p2Client = null;
190
- p2Username = null;
208
+ p2Client = null;
209
+ p2Username = null;
210
+ clearP2Grace();
191
211
  clearP2Timeout();
192
212
  broadcastAll({ type: 'player2-left', username: leaving, reason: 'timeout' });
193
213
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
@@ -195,14 +215,25 @@ export function createInputServer(opts = {}) {
195
215
 
196
216
  // ── Host reconnect grace period helpers ───────────────────────────────────
197
217
  function clearGrace() {
198
- if (graceTimer) { clearTimeout(graceTimer); graceTimer = null; }
218
+ if (graceTimer) {
219
+ clearTimeout(graceTimer);
220
+ graceTimer = null;
221
+ }
199
222
  pendingHostUsername = null;
200
223
  }
201
224
 
225
+ function clearP2Grace() {
226
+ if (p2GraceTimer) {
227
+ clearTimeout(p2GraceTimer);
228
+ p2GraceTimer = null;
229
+ }
230
+ pendingP2Username = null;
231
+ }
232
+
202
233
  // Called when grace expires without the host reconnecting.
203
234
  function expireGrace() {
204
- graceTimer = null;
205
- const leaving = pendingHostUsername;
235
+ graceTimer = null;
236
+ const leaving = pendingHostUsername;
206
237
  pendingHostUsername = null;
207
238
  if (verbose) console.error(`[input-server] host grace expired for ${leaving}`);
208
239
  logEv('host-grace-expired', { username: leaving });
@@ -214,13 +245,37 @@ export function createInputServer(opts = {}) {
214
245
  function onHostDisconnect(leaving) {
215
246
  clearGrace();
216
247
  pendingHostUsername = leaving;
217
- if (verbose) console.error(`[input-server] host ${leaving} disconnected — grace ${HOST_RECONNECT_GRACE}ms`);
248
+ if (verbose)
249
+ console.error(
250
+ `[input-server] host ${leaving} disconnected — grace ${HOST_RECONNECT_GRACE}ms`,
251
+ );
218
252
  logEv('host-disconnected', { username: leaving, graceMs: HOST_RECONNECT_GRACE });
219
253
  // Tell everyone the host is temporarily gone; P2 should wait before acting.
220
254
  broadcastAll({ type: 'host-disconnected', username: leaving, graceMs: HOST_RECONNECT_GRACE });
221
255
  graceTimer = setTimeout(expireGrace, HOST_RECONNECT_GRACE);
222
256
  }
223
257
 
258
+ function expireP2Grace() {
259
+ p2GraceTimer = null;
260
+ const leaving = pendingP2Username;
261
+ pendingP2Username = null;
262
+ if (verbose) console.error(`[input-server] p2 grace expired for ${leaving}`);
263
+ logEv('p2-grace-expired', { username: leaving });
264
+ broadcastAll({ type: 'player2-left', username: leaving, reason: 'disconnect' });
265
+ broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
266
+ }
267
+
268
+ function onP2Disconnect(leaving) {
269
+ clearP2Grace();
270
+ pendingP2Username = leaving;
271
+ if (verbose)
272
+ console.error(
273
+ `[input-server] player2 ${leaving} disconnected — grace ${P2_RECONNECT_GRACE}ms`,
274
+ );
275
+ logEv('p2-disconnected', { username: leaving, graceMs: P2_RECONNECT_GRACE });
276
+ p2GraceTimer = setTimeout(expireP2Grace, P2_RECONNECT_GRACE);
277
+ }
278
+
224
279
  function kickHostForInactivity() {
225
280
  if (!hostClient) return;
226
281
  if (verbose) console.error(`[input-server] host ${hostUsername} timed out due to inactivity`);
@@ -231,9 +286,9 @@ export function createInputServer(opts = {}) {
231
286
  }
232
287
  const leaving = hostUsername;
233
288
  setWsIdentity(hostClient, 'spectator', null);
234
- hostClient = null;
235
- hostUsername = null;
236
- inviteToken = null;
289
+ hostClient = null;
290
+ hostUsername = null;
291
+ inviteToken = null;
237
292
  portOverrideEnabled = false;
238
293
  overrideHostPort = 2;
239
294
  overrideP2Port = 1;
@@ -253,7 +308,9 @@ export function createInputServer(opts = {}) {
253
308
  clearHostTimeout();
254
309
  clearGrace();
255
310
  if (targetWs.readyState === targetWs.OPEN) {
256
- try { targetWs.send(JSON.stringify({ type: 'host-kicked', reason })); } catch (_) {}
311
+ try {
312
+ targetWs.send(JSON.stringify({ type: 'host-kicked', reason }));
313
+ } catch (_) {}
257
314
  }
258
315
  hostClient = null;
259
316
  hostUsername = null;
@@ -276,9 +333,12 @@ export function createInputServer(opts = {}) {
276
333
  const addr = targetMeta?.addr ?? null;
277
334
  const leaving = p2Username;
278
335
  if (targetWs.readyState === targetWs.OPEN) {
279
- try { targetWs.send(JSON.stringify({ type: 'kicked', reason })); } catch (_) {}
336
+ try {
337
+ targetWs.send(JSON.stringify({ type: 'kicked', reason }));
338
+ } catch (_) {}
280
339
  }
281
340
  clearP2Timeout();
341
+ clearP2Grace();
282
342
  p2Client = null;
283
343
  p2Username = null;
284
344
  setWsIdentity(targetWs, 'spectator', null);
@@ -288,7 +348,6 @@ export function createInputServer(opts = {}) {
288
348
  return { kicked: true, username: leaving, addr };
289
349
  }
290
350
 
291
-
292
351
  function broadcastExcept(excludeWs, msg) {
293
352
  const raw = JSON.stringify(msg);
294
353
  wss.clients.forEach((c) => {
@@ -298,13 +357,18 @@ export function createInputServer(opts = {}) {
298
357
 
299
358
  function broadcastAll(msg) {
300
359
  const raw = JSON.stringify(msg);
301
- wss.clients.forEach((c) => { if (c.readyState === c.OPEN) c.send(raw); });
360
+ wss.clients.forEach((c) => {
361
+ if (c.readyState === c.OPEN) c.send(raw);
362
+ });
302
363
  }
303
364
 
304
365
  // True when the P2 slot is available for open joining
305
366
  function isP2SlotOpen() {
306
- return !!(hostClient && hostClient.readyState === hostClient.OPEN)
307
- && !(p2Client && p2Client.readyState === p2Client.OPEN);
367
+ return (
368
+ !!(hostClient && hostClient.readyState === hostClient.OPEN) &&
369
+ !(p2Client && p2Client.readyState === p2Client.OPEN) &&
370
+ !p2GraceTimer
371
+ );
308
372
  }
309
373
 
310
374
  let clientCount = 0;
@@ -363,18 +427,22 @@ export function createInputServer(opts = {}) {
363
427
  const anonymousWebrtcPeers = Math.max(0, webrtcTotal - mappedWebrtcPeers);
364
428
 
365
429
  return {
366
- host: hostClient ? {
367
- connected: hostClient.readyState === hostClient.OPEN,
368
- username: hostUsername,
369
- addr: hostMeta?.addr ?? null,
370
- webrtcPeers: hostMeta?.addr ? (webrtcByAddr.get(hostMeta.addr) ?? 0) : 0,
371
- } : null,
372
- p2: p2Client ? {
373
- connected: p2Client.readyState === p2Client.OPEN,
374
- username: p2Username,
375
- addr: p2Meta?.addr ?? null,
376
- webrtcPeers: p2Meta?.addr ? (webrtcByAddr.get(p2Meta.addr) ?? 0) : 0,
377
- } : null,
430
+ host: hostClient
431
+ ? {
432
+ connected: hostClient.readyState === hostClient.OPEN,
433
+ username: hostUsername,
434
+ addr: hostMeta?.addr ?? null,
435
+ webrtcPeers: hostMeta?.addr ? (webrtcByAddr.get(hostMeta.addr) ?? 0) : 0,
436
+ }
437
+ : null,
438
+ p2: p2Client
439
+ ? {
440
+ connected: p2Client.readyState === p2Client.OPEN,
441
+ username: p2Username,
442
+ addr: p2Meta?.addr ?? null,
443
+ webrtcPeers: p2Meta?.addr ? (webrtcByAddr.get(p2Meta.addr) ?? 0) : 0,
444
+ }
445
+ : null,
378
446
  spectators,
379
447
  counts: {
380
448
  inputClients: clientCount,
@@ -402,7 +470,8 @@ export function createInputServer(opts = {}) {
402
470
  clientCount++;
403
471
  const addr = req.socket.remoteAddress;
404
472
  clientMeta.set(ws, { addr: normalizeAddr(addr), role: 'spectator', username: null });
405
- if (verbose) console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
473
+ if (verbose)
474
+ console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
406
475
  logEv('client-connected', { addr, total: clientCount });
407
476
 
408
477
  ws.on('message', (data) => {
@@ -419,7 +488,9 @@ export function createInputServer(opts = {}) {
419
488
  // main thread causes a noticeable pause proportional to file size.
420
489
  if (verbose) {
421
490
  if (msg.type === 'load-crt') {
422
- console.error(`[input-server] rx: load-crt filename=${msg.filename ?? '?'} dataLen=${(msg.data ?? '').length}`);
491
+ console.error(
492
+ `[input-server] rx: load-crt filename=${msg.filename ?? '?'} dataLen=${(msg.data ?? '').length}`,
493
+ );
423
494
  } else {
424
495
  console.error(`[input-server] rx:`, JSON.stringify(msg));
425
496
  }
@@ -433,7 +504,10 @@ export function createInputServer(opts = {}) {
433
504
  // the new browser tab gets host-taken and detach/reset silently fail.
434
505
  if (!msg.force) {
435
506
  ws.send(JSON.stringify({ type: 'host-taken' }));
436
- logEv('host-claim-rejected', { reason: 'slot-taken', username: msg.username ?? 'player' });
507
+ logEv('host-claim-rejected', {
508
+ reason: 'slot-taken',
509
+ username: msg.username ?? 'player',
510
+ });
437
511
  return;
438
512
  }
439
513
  // Forcibly evict the existing host before granting the new claim.
@@ -441,29 +515,49 @@ export function createInputServer(opts = {}) {
441
515
  logEv('host-force-evicted', { evicted: hostUsername, by: msg.username ?? 'player' });
442
516
  clearHostTimeout();
443
517
  clearGrace();
444
- try { hostClient.send(JSON.stringify({ type: 'host-evicted', reason: 'force-claim' })); } catch (_) {}
445
- try { hostClient.close(); } catch (_) {}
518
+ try {
519
+ hostClient.send(JSON.stringify({ type: 'host-evicted', reason: 'force-claim' }));
520
+ } catch (_) {}
521
+ try {
522
+ hostClient.close();
523
+ } catch (_) {}
446
524
  setWsIdentity(hostClient, 'spectator', null);
447
- hostClient = null;
525
+ hostClient = null;
448
526
  hostUsername = null;
449
- inviteToken = null;
527
+ inviteToken = null;
450
528
  }
451
529
  const isRejoin = graceTimer && pendingHostUsername === (msg.username ?? 'player');
452
530
  if (graceTimer) clearGrace(); // cancel grace regardless of who's claiming
453
- hostClient = ws;
531
+ hostClient = ws;
454
532
  hostUsername = msg.username ?? 'player';
455
533
  setWsIdentity(ws, 'host', hostUsername);
456
- ws.send(JSON.stringify({
457
- type: 'host-confirmed', username: hostUsername, joystickPort: hostPort(),
458
- player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
459
- }));
534
+ ws.send(
535
+ JSON.stringify({
536
+ type: 'host-confirmed',
537
+ username: hostUsername,
538
+ joystickPort: hostPort(),
539
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
540
+ }),
541
+ );
460
542
  if (isRejoin) {
461
- broadcastExcept(ws, { type: 'host-rejoined', username: hostUsername, joystickPort: hostPort() });
543
+ broadcastExcept(ws, {
544
+ type: 'host-rejoined',
545
+ username: hostUsername,
546
+ joystickPort: hostPort(),
547
+ });
462
548
  } else {
463
- broadcastExcept(ws, { type: 'host-joined', username: hostUsername, joystickPort: hostPort() });
549
+ broadcastExcept(ws, {
550
+ type: 'host-joined',
551
+ username: hostUsername,
552
+ joystickPort: hostPort(),
553
+ });
464
554
  }
465
- if (verbose) console.error(`[input-server] host ${isRejoin ? 're' : ''}claimed by ${hostUsername}`);
466
- logEv(isRejoin ? 'host-rejoined' : 'host-joined', { username: hostUsername, joystickPort: hostPort() });
555
+ if (verbose)
556
+ console.error(`[input-server] host ${isRejoin ? 're' : ''}claimed by ${hostUsername}`);
557
+ logEv(isRejoin ? 'host-rejoined' : 'host-joined', {
558
+ username: hostUsername,
559
+ joystickPort: hostPort(),
560
+ });
467
561
  resetHostTimeout();
468
562
  // P2 slot just opened (host present, no P2)
469
563
  broadcastExcept(ws, { type: 'p2-slot-status', open: isP2SlotOpen() });
@@ -474,13 +568,14 @@ export function createInputServer(opts = {}) {
474
568
  if (msg.type === 'swap-ports') {
475
569
  if (ws !== hostClient) return;
476
570
  portsSwapped = !portsSwapped;
477
- if (verbose) console.error(`[input-server] ports swapped: host=${hostPort()} p2=${p2Port()}`);
571
+ if (verbose)
572
+ console.error(`[input-server] ports swapped: host=${hostPort()} p2=${p2Port()}`);
478
573
  logEv('ports-swapped', { hostPort: hostPort(), p2Port: p2Port() });
479
574
  broadcastAll({
480
- type: 'ports-swapped',
481
- swapped: portsSwapped,
482
- hostPort: hostPort(),
483
- p2Port: p2Port(),
575
+ type: 'ports-swapped',
576
+ swapped: portsSwapped,
577
+ hostPort: hostPort(),
578
+ p2Port: p2Port(),
484
579
  });
485
580
  return;
486
581
  }
@@ -491,9 +586,18 @@ export function createInputServer(opts = {}) {
491
586
  const enabled = !!msg.enabled;
492
587
  const hp = Number(msg.hostPort);
493
588
  const pp = Number(msg.p2Port);
494
- if (!Number.isFinite(hp) || !Number.isFinite(pp) || (hp !== 1 && hp !== 2) || (pp !== 1 && pp !== 2)) {
589
+ if (
590
+ !Number.isFinite(hp) ||
591
+ !Number.isFinite(pp) ||
592
+ (hp !== 1 && hp !== 2) ||
593
+ (pp !== 1 && pp !== 2)
594
+ ) {
495
595
  if (verbose) console.error('[input-server] invalid set-port-override payload');
496
- logEv('error', { kind: 'set-port-override-invalid', hostPort: msg.hostPort, p2Port: msg.p2Port });
596
+ logEv('error', {
597
+ kind: 'set-port-override-invalid',
598
+ hostPort: msg.hostPort,
599
+ p2Port: msg.p2Port,
600
+ });
497
601
  return;
498
602
  }
499
603
  portOverrideEnabled = enabled;
@@ -520,9 +624,9 @@ export function createInputServer(opts = {}) {
520
624
  if (msg.type === 'p2-leave') {
521
625
  if (ws === p2Client) {
522
626
  clearP2Timeout();
523
- p2Client = null;
524
- const leaving = p2Username;
525
- p2Username = null;
627
+ p2Client = null;
628
+ const leaving = p2Username;
629
+ p2Username = null;
526
630
  setWsIdentity(ws, 'spectator', null);
527
631
  if (verbose) console.error(`[input-server] player2 ${leaving} voluntarily left`);
528
632
  logEv('p2-left', { username: leaving, reason: 'voluntary' });
@@ -538,11 +642,11 @@ export function createInputServer(opts = {}) {
538
642
  if (ws === hostClient) {
539
643
  clearHostTimeout();
540
644
  clearGrace();
541
- hostClient = null;
542
- const leaving = hostUsername;
543
- hostUsername = null;
544
- inviteToken = null;
545
- portsSwapped = false;
645
+ hostClient = null;
646
+ const leaving = hostUsername;
647
+ hostUsername = null;
648
+ inviteToken = null;
649
+ portsSwapped = false;
546
650
  portOverrideEnabled = false;
547
651
  overrideHostPort = 2;
548
652
  overrideP2Port = 1;
@@ -559,7 +663,7 @@ export function createInputServer(opts = {}) {
559
663
  // ── Host issues a player-2 invite ─────────────────────────────────────
560
664
  if (msg.type === 'invite-p2') {
561
665
  if (ws !== hostClient) return;
562
- if (p2Client && p2Client.readyState === p2Client.OPEN) {
666
+ if ((p2Client && p2Client.readyState === p2Client.OPEN) || p2GraceTimer) {
563
667
  ws.send(JSON.stringify({ type: 'invite-p2-error', reason: 'slot-taken' }));
564
668
  logEv('invite-p2-rejected', { reason: 'slot-taken' });
565
669
  return;
@@ -583,22 +687,50 @@ export function createInputServer(opts = {}) {
583
687
  logEv('p2-join-rejected', { reason: 'slot-taken', username: msg.username ?? 'player2' });
584
688
  return;
585
689
  }
690
+ const requestedUsername = msg.username ?? 'player2';
691
+ const isRejoin = !!p2GraceTimer && pendingP2Username === requestedUsername;
692
+ if (p2GraceTimer && !isRejoin) {
693
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
694
+ logEv('p2-join-rejected', {
695
+ reason: 'slot-pending-rejoin',
696
+ username: requestedUsername,
697
+ pending: pendingP2Username ?? '-',
698
+ });
699
+ return;
700
+ }
701
+ if (isRejoin) clearP2Grace();
586
702
  if (ws === hostClient) {
587
703
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'already-host' }));
588
704
  return;
589
705
  }
590
- p2Client = ws;
591
- p2Username = msg.username ?? 'player2';
706
+ p2Client = ws;
707
+ p2Username = requestedUsername;
592
708
  inviteToken = null;
593
709
  setWsIdentity(ws, 'p2', p2Username);
594
- ws.send(JSON.stringify({
595
- type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
596
- }));
597
- broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
710
+ ws.send(
711
+ JSON.stringify({
712
+ type: 'join-p2-confirmed',
713
+ username: p2Username,
714
+ joystickPort: p2Port(),
715
+ }),
716
+ );
717
+ broadcastExcept(ws, {
718
+ type: 'player2-joined',
719
+ username: p2Username,
720
+ joystickPort: p2Port(),
721
+ });
598
722
  // Notify all clients that the slot is now taken
599
723
  broadcastAll({ type: 'p2-slot-status', open: false });
600
- if (verbose) console.error(`[input-server] player2 open-joined: ${p2Username}`);
601
- logEv('p2-joined', { username: p2Username, joystickPort: p2Port(), method: 'open' });
724
+ if (verbose) {
725
+ console.error(
726
+ `[input-server] player2 ${isRejoin ? 're' : ''}joined (open): ${p2Username}`,
727
+ );
728
+ }
729
+ logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
730
+ username: p2Username,
731
+ joystickPort: p2Port(),
732
+ method: 'open',
733
+ });
602
734
  resetP2Timeout();
603
735
  return;
604
736
  }
@@ -607,24 +739,55 @@ export function createInputServer(opts = {}) {
607
739
  if (msg.type === 'join-p2') {
608
740
  if (!inviteToken || msg.token !== inviteToken) {
609
741
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'invalid-token' }));
610
- logEv('p2-join-rejected', { reason: 'invalid-token', username: msg.username ?? 'player2' });
742
+ logEv('p2-join-rejected', {
743
+ reason: 'invalid-token',
744
+ username: msg.username ?? 'player2',
745
+ });
611
746
  return;
612
747
  }
613
748
  if (p2Client && p2Client.readyState === p2Client.OPEN) {
614
749
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
615
750
  return;
616
751
  }
617
- p2Client = ws;
618
- p2Username = msg.username ?? 'player2';
752
+ const requestedUsername = msg.username ?? 'player2';
753
+ const isRejoin = !!p2GraceTimer && pendingP2Username === requestedUsername;
754
+ if (p2GraceTimer && !isRejoin) {
755
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
756
+ logEv('p2-join-rejected', {
757
+ reason: 'slot-pending-rejoin',
758
+ username: requestedUsername,
759
+ pending: pendingP2Username ?? '-',
760
+ });
761
+ return;
762
+ }
763
+ if (isRejoin) clearP2Grace();
764
+ p2Client = ws;
765
+ p2Username = requestedUsername;
619
766
  inviteToken = null;
620
767
  setWsIdentity(ws, 'p2', p2Username);
621
- ws.send(JSON.stringify({
622
- type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
623
- }));
624
- broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
768
+ ws.send(
769
+ JSON.stringify({
770
+ type: 'join-p2-confirmed',
771
+ username: p2Username,
772
+ joystickPort: p2Port(),
773
+ }),
774
+ );
775
+ broadcastExcept(ws, {
776
+ type: 'player2-joined',
777
+ username: p2Username,
778
+ joystickPort: p2Port(),
779
+ });
625
780
  broadcastAll({ type: 'p2-slot-status', open: false });
626
- if (verbose) console.error(`[input-server] player2 joined: ${p2Username}`);
627
- logEv('p2-joined', { username: p2Username, joystickPort: p2Port(), method: 'token' });
781
+ if (verbose) {
782
+ console.error(
783
+ `[input-server] player2 ${isRejoin ? 're' : ''}joined (token): ${p2Username}`,
784
+ );
785
+ }
786
+ logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
787
+ username: p2Username,
788
+ joystickPort: p2Port(),
789
+ method: 'token',
790
+ });
628
791
  resetP2Timeout();
629
792
  return;
630
793
  }
@@ -637,11 +800,19 @@ export function createInputServer(opts = {}) {
637
800
  p2Client.send(JSON.stringify({ type: 'kicked' }));
638
801
  }
639
802
  const leaving = p2Username;
803
+ const pendingLeaving = pendingP2Username;
640
804
  clearP2Timeout();
641
- p2Client = null;
642
- p2Username = null;
805
+ clearP2Grace();
806
+ p2Client = null;
807
+ p2Username = null;
643
808
  setWsIdentity(ws, 'spectator', null);
644
- if (leaving) broadcastAll({ type: 'player2-left', username: leaving });
809
+ if (leaving || pendingLeaving) {
810
+ broadcastAll({
811
+ type: 'player2-left',
812
+ username: leaving ?? pendingLeaving,
813
+ reason: 'revoked',
814
+ });
815
+ }
645
816
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
646
817
  if (verbose) console.error(`[input-server] p2 revoked by host`);
647
818
  logEv('p2-kicked', { username: leaving ?? '?', by: 'host' });
@@ -652,51 +823,80 @@ export function createInputServer(opts = {}) {
652
823
  if (msg.type === 'admin-status') {
653
824
  const valid = validateAdminToken(msg.token ?? '');
654
825
  if (!valid) {
655
- ws.send(JSON.stringify({ type: 'admin-error', command: 'status', reason: 'invalid-token' }));
826
+ ws.send(
827
+ JSON.stringify({ type: 'admin-error', command: 'status', reason: 'invalid-token' }),
828
+ );
656
829
  return;
657
830
  }
658
831
  setWsIdentity(ws, 'admin', null);
659
- ws.send(JSON.stringify({
660
- type: 'admin-status-ok',
661
- status: buildAdminStatus(),
662
- }));
832
+ ws.send(
833
+ JSON.stringify({
834
+ type: 'admin-status-ok',
835
+ status: buildAdminStatus(),
836
+ }),
837
+ );
663
838
  return;
664
839
  }
665
840
 
666
841
  if (msg.type === 'admin-kick-player') {
667
842
  const valid = validateAdminToken(msg.token ?? '');
668
843
  if (!valid) {
669
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-token' }));
844
+ ws.send(
845
+ JSON.stringify({
846
+ type: 'admin-error',
847
+ command: 'kick-player',
848
+ reason: 'invalid-token',
849
+ }),
850
+ );
670
851
  return;
671
852
  }
672
853
  setWsIdentity(ws, 'admin', null);
673
- const target = msg.target === 'p2' ? 'p2' : (msg.target === 'host' ? 'host' : null);
854
+ const target = msg.target === 'p2' ? 'p2' : msg.target === 'host' ? 'host' : null;
674
855
  if (!target) {
675
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-target' }));
856
+ ws.send(
857
+ JSON.stringify({
858
+ type: 'admin-error',
859
+ command: 'kick-player',
860
+ reason: 'invalid-target',
861
+ }),
862
+ );
676
863
  return;
677
864
  }
678
- const result = target === 'host'
679
- ? kickHostByReason('admin-kick')
680
- : kickP2ByReason('admin-kick');
865
+ const result =
866
+ target === 'host' ? kickHostByReason('admin-kick') : kickP2ByReason('admin-kick');
681
867
  if (!result.kicked) {
682
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'target-not-present', target }));
868
+ ws.send(
869
+ JSON.stringify({
870
+ type: 'admin-error',
871
+ command: 'kick-player',
872
+ reason: 'target-not-present',
873
+ target,
874
+ }),
875
+ );
683
876
  return;
684
877
  }
685
- logEv(target === 'host' ? 'host-kicked' : 'p2-kicked', { username: result.username ?? '-', by: 'admin-cli' });
686
- ws.send(JSON.stringify({
687
- type: 'admin-kick-player-ok',
688
- target,
689
- username: result.username,
690
- addr: result.addr,
691
- status: buildAdminStatus(),
692
- }));
878
+ logEv(target === 'host' ? 'host-kicked' : 'p2-kicked', {
879
+ username: result.username ?? '-',
880
+ by: 'admin-cli',
881
+ });
882
+ ws.send(
883
+ JSON.stringify({
884
+ type: 'admin-kick-player-ok',
885
+ target,
886
+ username: result.username,
887
+ addr: result.addr,
888
+ status: buildAdminStatus(),
889
+ }),
890
+ );
693
891
  return;
694
892
  }
695
893
 
696
894
  if (msg.type === 'admin-kick-all') {
697
895
  const valid = validateAdminToken(msg.token ?? '');
698
896
  if (!valid) {
699
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-all', reason: 'invalid-token' }));
897
+ ws.send(
898
+ JSON.stringify({ type: 'admin-error', command: 'kick-all', reason: 'invalid-token' }),
899
+ );
700
900
  return;
701
901
  }
702
902
  setWsIdentity(ws, 'admin', null);
@@ -714,18 +914,21 @@ export function createInputServer(opts = {}) {
714
914
  const meta = clientMeta.get(c);
715
915
  if (meta?.role === 'admin') continue;
716
916
  try {
717
- if (c.readyState === c.OPEN) c.send(JSON.stringify({ type: 'kicked', reason: 'admin-kick-all' }));
917
+ if (c.readyState === c.OPEN)
918
+ c.send(JSON.stringify({ type: 'kicked', reason: 'admin-kick-all' }));
718
919
  c.close();
719
920
  kicked.spectators++;
720
921
  } catch (_) {}
721
922
  }
722
923
  kicked.webrtcPeers = disconnectAllWebrtcPeers('admin-kick-all');
723
924
  logEv('admin-kick-all', { spectators: kicked.spectators, webrtcPeers: kicked.webrtcPeers });
724
- ws.send(JSON.stringify({
725
- type: 'admin-kick-all-ok',
726
- kicked,
727
- status: buildAdminStatus(),
728
- }));
925
+ ws.send(
926
+ JSON.stringify({
927
+ type: 'admin-kick-all-ok',
928
+ kicked,
929
+ status: buildAdminStatus(),
930
+ }),
931
+ );
729
932
  return;
730
933
  }
731
934
 
@@ -759,7 +962,8 @@ export function createInputServer(opts = {}) {
759
962
  if (ws !== hostClient) return;
760
963
  const loadFilename = msg.filename ?? '';
761
964
  const fileType = msg.fileType ?? 'crt';
762
- if (verbose) console.error(`[input-server] load-file: ${loadFilename || '?'} (${fileType})`);
965
+ if (verbose)
966
+ console.error(`[input-server] load-file: ${loadFilename || '?'} (${fileType})`);
763
967
  logEv('cmd-load-file', {
764
968
  filename: loadFilename || '?',
765
969
  fileType,
@@ -767,7 +971,14 @@ export function createInputServer(opts = {}) {
767
971
  });
768
972
  broadcastAll({ type: 'cart-loading', filename: loadFilename });
769
973
  Promise.resolve()
770
- .then(() => onCommand({ type: 'load-file', filename: loadFilename, fileType, data: msg.data ?? '' }))
974
+ .then(() =>
975
+ onCommand({
976
+ type: 'load-file',
977
+ filename: loadFilename,
978
+ fileType,
979
+ data: msg.data ?? '',
980
+ }),
981
+ )
771
982
  .then(() => {
772
983
  currentCartFilename = loadFilename || null;
773
984
  broadcastAll({ type: 'cart-loaded', filename: loadFilename });
@@ -792,7 +1003,14 @@ export function createInputServer(opts = {}) {
792
1003
  const loadFilename = msg.filename ?? '';
793
1004
  broadcastAll({ type: 'cart-loading', filename: loadFilename });
794
1005
  Promise.resolve()
795
- .then(() => onCommand({ type: 'load-file', filename: loadFilename, fileType: 'crt', data: msg.data ?? '' }))
1006
+ .then(() =>
1007
+ onCommand({
1008
+ type: 'load-file',
1009
+ filename: loadFilename,
1010
+ fileType: 'crt',
1011
+ data: msg.data ?? '',
1012
+ }),
1013
+ )
796
1014
  .then(() => {
797
1015
  currentCartFilename = loadFilename || null;
798
1016
  broadcastAll({ type: 'cart-loaded', filename: loadFilename });
@@ -800,7 +1018,11 @@ export function createInputServer(opts = {}) {
800
1018
  .catch((e) => {
801
1019
  broadcastAll({ type: 'cart-load-error', reason: String(e?.message ?? e) });
802
1020
  if (verbose) console.error('[input-server] load-crt error:', e);
803
- logEv('error', { kind: 'load-crt-failed', filename: loadFilename, err: String(e?.message ?? e) });
1021
+ logEv('error', {
1022
+ kind: 'load-crt-failed',
1023
+ filename: loadFilename,
1024
+ err: String(e?.message ?? e),
1025
+ });
804
1026
  });
805
1027
  return;
806
1028
  }
@@ -838,11 +1060,28 @@ export function createInputServer(opts = {}) {
838
1060
  return;
839
1061
  }
840
1062
 
1063
+ if (msg.type === 'reboot') {
1064
+ if (ws !== hostClient) return;
1065
+ if (verbose) console.error('[input-server] reboot');
1066
+ logEv('cmd-reboot', { host: hostUsername });
1067
+ Promise.resolve()
1068
+ .then(() => onCommand({ type: 'reboot' }))
1069
+ .then(() => {
1070
+ currentCartFilename = null;
1071
+ broadcastAll({ type: 'machine-rebooted' });
1072
+ })
1073
+ .catch((e) => {
1074
+ if (verbose) console.error('[input-server] reboot error:', e);
1075
+ logEv('error', { kind: 'reboot-failed', err: String(e?.message ?? e) });
1076
+ });
1077
+ return;
1078
+ }
1079
+
841
1080
  // ── Input events ─────────────────────────────────────────────────────
842
1081
  if (msg.type === 'joystick' || msg.type === 'key') {
843
1082
  if (ws !== hostClient && ws !== p2Client) return;
844
1083
  if (ws === hostClient) resetHostTimeout();
845
- if (ws === p2Client) resetP2Timeout();
1084
+ if (ws === p2Client) resetP2Timeout();
846
1085
  // Track input counts for flood investigation
847
1086
  const role = ws === hostClient ? 'host' : 'p2';
848
1087
  const stats = role === 'host' ? _inputStats.host : _inputStats.p2;
@@ -862,37 +1101,44 @@ export function createInputServer(opts = {}) {
862
1101
  if (!_latencyLogTimer) {
863
1102
  _latencyLogTimer = setInterval(() => {
864
1103
  const hostActive = _latencyCount.host > 0;
865
- const p2Active = _latencyCount.p2 > 0;
1104
+ const p2Active = _latencyCount.p2 > 0;
866
1105
  if (hostActive || p2Active) {
867
1106
  const hostAvg = hostActive ? Number(_avgLatency.host.toFixed(0)) : null;
868
- const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
1107
+ const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
869
1108
  const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
870
- const p2Label = p2Avg != null ? `${p2Avg}` : '--';
1109
+ const p2Label = p2Avg != null ? `${p2Avg}` : '--';
871
1110
  if (logEvents || verbose) {
872
- console.error(`[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`);
1111
+ console.error(
1112
+ `[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`,
1113
+ );
873
1114
  }
874
1115
  _networkStats.host.avgLatency = hostAvg;
875
- _networkStats.p2.avgLatency = p2Avg;
1116
+ _networkStats.p2.avgLatency = p2Avg;
876
1117
  broadcastNetworkStats();
877
1118
  }
878
1119
  // Reset averages
879
- _avgLatency.host = 0; _avgLatency.p2 = 0;
880
- _latencyCount.host = 0; _latencyCount.p2 = 0;
1120
+ _avgLatency.host = 0;
1121
+ _avgLatency.p2 = 0;
1122
+ _latencyCount.host = 0;
1123
+ _latencyCount.p2 = 0;
881
1124
  }, 5000);
882
1125
  }
883
1126
  // Accumulate for averaging
884
1127
  _latencyCount[role]++;
885
- _avgLatency[role] = ((_avgLatency[role] * (_latencyCount[role] - 1)) + latency) / _latencyCount[role];
1128
+ _avgLatency[role] =
1129
+ (_avgLatency[role] * (_latencyCount[role] - 1) + latency) / _latencyCount[role];
886
1130
  if (latency > LATENCY_SPIKE_MS) {
887
1131
  if (bucket) {
888
1132
  bucket.lastSpikeLatency = latency;
889
1133
  bucket.lastSpikeAt = now;
890
1134
  }
891
1135
  if (logEvents || verbose) {
892
- console.error(`[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
893
- `dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`);
894
- }
1136
+ console.error(
1137
+ `[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
1138
+ `dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`,
1139
+ );
895
1140
  }
1141
+ }
896
1142
  }
897
1143
 
898
1144
  // Tag with role so onInput can include it in logEvents output
@@ -911,7 +1157,7 @@ export function createInputServer(opts = {}) {
911
1157
  }
912
1158
 
913
1159
  if (msg.type === 'ping') {
914
- const role = ws === hostClient ? 'host' : (ws === p2Client ? 'p2' : 'spectator');
1160
+ const role = ws === hostClient ? 'host' : ws === p2Client ? 'p2' : 'spectator';
915
1161
  const now = Date.now();
916
1162
  const payload = {
917
1163
  type: 'pong',
@@ -919,7 +1165,9 @@ export function createInputServer(opts = {}) {
919
1165
  serverTime: now,
920
1166
  clientTime: msg.clientTime ?? null,
921
1167
  };
922
- try { ws.send(JSON.stringify(payload)); } catch (_) {}
1168
+ try {
1169
+ ws.send(JSON.stringify(payload));
1170
+ } catch (_) {}
923
1171
  if (verbose) console.error(`[ping] role=${role} pong pingId=${msg.pingId ?? '-'} `);
924
1172
  return;
925
1173
  }
@@ -932,11 +1180,11 @@ export function createInputServer(opts = {}) {
932
1180
 
933
1181
  if (ws === hostClient) {
934
1182
  clearHostTimeout();
935
- hostClient = null;
1183
+ hostClient = null;
936
1184
  const leaving = hostUsername;
937
- hostUsername = null;
938
- inviteToken = null;
939
- portsSwapped = false;
1185
+ hostUsername = null;
1186
+ inviteToken = null;
1187
+ portsSwapped = false;
940
1188
  portOverrideEnabled = false;
941
1189
  overrideHostPort = 2;
942
1190
  overrideP2Port = 1;
@@ -945,13 +1193,10 @@ export function createInputServer(opts = {}) {
945
1193
 
946
1194
  if (ws === p2Client) {
947
1195
  clearP2Timeout();
948
- p2Client = null;
1196
+ p2Client = null;
949
1197
  const leaving = p2Username;
950
- p2Username = null;
951
- if (verbose) console.error(`[input-server] player2 ${leaving} disconnected`);
952
- logEv('p2-disconnected', { username: leaving, total: clientCount });
953
- broadcastExcept(ws, { type: 'player2-left', username: leaving });
954
- broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
1198
+ p2Username = null;
1199
+ onP2Disconnect(leaving);
955
1200
  }
956
1201
  clientMeta.delete(ws);
957
1202
  });
@@ -964,30 +1209,39 @@ export function createInputServer(opts = {}) {
964
1209
  // ── Hello handshake ───────────────────────────────────────────────────
965
1210
  const hostActive = !!(hostClient && hostClient.readyState === hostClient.OPEN);
966
1211
  const serverTime = Date.now();
967
- ws.send(JSON.stringify({
968
- type: 'hello',
969
- protocol: 'c64-input',
970
- version: 1,
971
- serverTime, // Unix ms for client clock sync
972
- // During grace period: treat slot as free so the original host can reclaim it.
973
- // hostPendingRejoin tells P2 (and spectators) to hold off.
974
- hostTaken: hostActive,
975
- hostPendingRejoin: !hostActive && !!graceTimer ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE } : null,
976
- host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
977
- player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
978
- p2SlotOpen: isP2SlotOpen(),
979
- portOverride: {
980
- enabled: portOverrideEnabled,
981
- hostPort: overrideHostPort,
982
- p2Port: overrideP2Port,
983
- effectiveHostPort: hostPort(),
984
- effectiveP2Port: p2Port(),
985
- },
986
- ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
987
- joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
988
- ...(serverVersion ? { serverVersion } : {}),
989
- ...(serverGitHash ? { serverGitHash } : {}),
990
- }));
1212
+ ws.send(
1213
+ JSON.stringify({
1214
+ type: 'hello',
1215
+ protocol: 'c64-input',
1216
+ version: 1,
1217
+ serverTime, // Unix ms for client clock sync
1218
+ // During grace period: treat slot as free so the original host can reclaim it.
1219
+ // hostPendingRejoin tells P2 (and spectators) to hold off.
1220
+ hostTaken: hostActive,
1221
+ hostPendingRejoin:
1222
+ !hostActive && !!graceTimer
1223
+ ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE }
1224
+ : null,
1225
+ host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
1226
+ p2PendingRejoin:
1227
+ !p2Client && !!p2GraceTimer
1228
+ ? { username: pendingP2Username, graceMs: P2_RECONNECT_GRACE }
1229
+ : null,
1230
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
1231
+ p2SlotOpen: isP2SlotOpen(),
1232
+ portOverride: {
1233
+ enabled: portOverrideEnabled,
1234
+ hostPort: overrideHostPort,
1235
+ p2Port: overrideP2Port,
1236
+ effectiveHostPort: hostPort(),
1237
+ effectiveP2Port: p2Port(),
1238
+ },
1239
+ ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
1240
+ joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
1241
+ ...(serverVersion ? { serverVersion } : {}),
1242
+ ...(serverGitHash ? { serverGitHash } : {}),
1243
+ }),
1244
+ );
991
1245
  });
992
1246
 
993
1247
  wss.on('error', (err) => {
@@ -995,15 +1249,26 @@ export function createInputServer(opts = {}) {
995
1249
  logEv('error', { kind: 'server-error', err: err.message });
996
1250
  });
997
1251
 
998
- const close = () => new Promise((resolve) => {
999
- clearHostTimeout();
1000
- clearP2Timeout();
1001
- clearGrace();
1002
- if (_inputLogTimer) { clearInterval(_inputLogTimer); _inputLogTimer = null; }
1003
- if (_latencyLogTimer) { clearInterval(_latencyLogTimer); _latencyLogTimer = null; }
1004
- if (_networkStatsTimer) { clearInterval(_networkStatsTimer); _networkStatsTimer = null; }
1005
- wss.close(() => resolve());
1006
- });
1252
+ const close = () =>
1253
+ new Promise((resolve) => {
1254
+ clearHostTimeout();
1255
+ clearP2Timeout();
1256
+ clearGrace();
1257
+ clearP2Grace();
1258
+ if (_inputLogTimer) {
1259
+ clearInterval(_inputLogTimer);
1260
+ _inputLogTimer = null;
1261
+ }
1262
+ if (_latencyLogTimer) {
1263
+ clearInterval(_latencyLogTimer);
1264
+ _latencyLogTimer = null;
1265
+ }
1266
+ if (_networkStatsTimer) {
1267
+ clearInterval(_networkStatsTimer);
1268
+ _networkStatsTimer = null;
1269
+ }
1270
+ wss.close(() => resolve());
1271
+ });
1007
1272
 
1008
1273
  return { wss, close };
1009
1274
  }