Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

7.5 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// A phone's screen seen from another computer (shared/phone-relay.js), an iPhone on a Mac's cable here.
// The host's side: a viewer's ios.screen.want, its GET (the viewer is the guest), the picture in scrcpy's
// packets (size, parameter sets, then frames from a keyframe on), its ios.input on the device's session,
// only from that viewer; ended with its session. The viewer's side: the window's input as ios.input.
// Run with: node --test shared/test/phone-relay.test.js
'use strict';

const assert = require('assert');
const { EventEmitter } = require('events');
const { test } = require('node:test');

const P = require('../protocol.js');
const { RelayScreen, ScreenHost, PULL } = require('../phone-relay.js');
const { HEADER } = require('../nativescreen.js');

const T = P.T;
const KEY = 'ab'.repeat(16);

function bus() {
  const handlers = new Map();
  const sent = [];
  return {
    sent,
    on: (t, fn) => handlers.set(t, fn),
    send: (to, m) => { sent.push([to, m]); return true; },
    fire: (t, m, from) => handlers.get(t)(m, from),
    onPeer: () => {},
    connectedIds: () => [],
  };
}

function iosSession() {
  const s = new EventEmitter();
  s.calls = [];
  s.size = { width: 750, height: 1334 };
  s.closed = false;
  s.touch = (a, p, x, y) => s.calls.push(['touch', a, x, y]);
  s.scroll = (x, y, w, h, hs, vs) => s.calls.push(['scroll', hs, vs]);
  s.keyCode = (c, d) => s.calls.push(['key', c, d]);
  s.tap = (k) => s.calls.push(['tap', k]);
  s.simple = (t) => s.calls.push(['simple', t]);
  return s;
}

function sink() {
  const out = new EventEmitter();
  out.chunks = [];
  out.writableLength = 0;
  out.write = (b) => out.chunks.push(Buffer.from(b));
  out.end = () => { out.ended = true; };
  out.writeHead = (code) => { out.code = code; };
  return out;
}

function packets(chunks) {
  const all = Buffer.concat(chunks);
  const out = [];
  for (let i = 0; i < all.length;) {
    const h = all.subarray(i, i + 12);
    if (h[0] & 0x80) { out.push(['size', h.readUInt32BE(4), h.readUInt32BE(8)]); i += 12; continue; }
    const f = h.readBigUInt64BE(0);
    const n = h.readUInt32BE(8);
    out.push([f & (1n << 62n) ? 'config' : f & (1n << 61n) ? 'key' : 'delta', all.subarray(i + 12, i + 12 + n).toString()]);
    i += 12 + n;
  }
  return out;
}

function host() {
  const b = bus();
  const s = iosSession();
  const used = [];
  const h = new ScreenHost({ hub: { bus: b, sessions: new Map() } }).add({
    find: (id) => (id === 'ios-usb-1' ? 'UDID1' : ''),
    use: (u) => { used.push(['use', u]); return s; },
    current: () => s,
    done: (u) => used.push(['done', u]),
  });
  return { h, b, s, used };
}

test('a viewer that pulls gets the size, the parameter sets, then frames from a keyframe on', () => {
  const { h, b, s, used } = host();
  s.emit('video', { config: true, data: Buffer.from('VPSSPSPPS') }); // before anyone watched: nothing
  b.fire(T.IOS_SCREEN_WANT, { on: true, id: 'ios-usb-1', key: KEY, pull: true }, 'ryzen');
  assert.deepStrictEqual(used, [['use', 'UDID1']]);
  s.emit('video', { config: true, data: Buffer.from('CFG') });
  const res = sink();
  assert.strictEqual(h.request({ url: PULL, method: 'GET', headers: { [HEADER]: KEY } }, res), true);
  assert.strictEqual(res.code, 200);
  assert.deepStrictEqual(s.calls.at(-1), ['simple', 17], 'a keyframe asked for');
  s.emit('video', { key: false, pts: 1, data: Buffer.from('d0') }); // before the keyframe: left out
  s.emit('video', { key: true, pts: 2, data: Buffer.from('k1') });
  s.emit('video', { key: false, pts: 3, data: Buffer.from('d1') });
  assert.deepStrictEqual(packets(res.chunks), [['size', 750, 1334], ['config', 'CFG'], ['key', 'k1'], ['delta', 'd1']]);
  assert.deepStrictEqual(b.sent.at(-1), ['ryzen', { t: T.IOS_SCREEN_STATE, key: KEY, on: true }]);
  // Behind: deltas wait for the next keyframe, asked for once.
  res.writableLength = 8 * 1024 * 1024;
  s.calls.length = 0;
  s.emit('video', { key: false, pts: 4, data: Buffer.from('d2') });
  s.emit('video', { key: false, pts: 5, data: Buffer.from('d3') });
  assert.deepStrictEqual(s.calls, [['simple', 17]]);
  res.writableLength = 0;
  s.emit('video', { key: true, pts: 6, data: Buffer.from('k2') });
  assert.deepStrictEqual(packets(res.chunks).slice(-1), [['key', 'k2']]);
});

test('a viewer that comes while the session runs gets its kept parameter sets first', () => {
  const { h, b, s } = host();
  s.config = Buffer.from('KEPT'); // sent once, before this viewer
  b.fire(T.IOS_SCREEN_WANT, { on: true, id: 'ios-usb-1', key: KEY, pull: true }, 'ryzen');
  const res = sink();
  h.request({ url: PULL, method: 'GET', headers: { [HEADER]: KEY } }, res);
  s.emit('video', { key: true, pts: 1, data: Buffer.from('k') });
  assert.deepStrictEqual(packets(res.chunks), [['size', 750, 1334], ['config', 'KEPT'], ['key', 'k']]);
});

test('its input goes to the device, only from that viewer; its session ending ends it', () => {
  const { h, b, s, used } = host();
  b.fire(T.IOS_SCREEN_WANT, { on: true, id: 'ios-usb-1', key: KEY, pull: true }, 'ryzen');
  h.request({ url: PULL, method: 'GET', headers: { [HEADER]: KEY } }, sink());
  s.calls.length = 0;
  b.fire(T.IOS_INPUT, { key: KEY, op: 'touch', a: 0, x: 0.5, y: 2 }, 'ryzen');
  b.fire(T.IOS_INPUT, { key: KEY, op: 'key', code: 'KeyA', down: true }, 'ryzen');
  b.fire(T.IOS_INPUT, { key: KEY, op: 'button', b: 3 }, 'ryzen');
  b.fire(T.IOS_INPUT, { key: KEY, op: 'touch', a: 0, x: 0, y: 0 }, 'nitro'); // not its viewer
  assert.deepStrictEqual(s.calls, [['touch', 0, 0.5, 1], ['key', 'KeyA', true], ['tap', 3]]);
  h.dropFrom('ryzen');
  assert.deepStrictEqual(used.at(-1), ['done', 'UDID1']);
  b.fire(T.IOS_INPUT, { key: KEY, op: 'button', b: 3 }, 'ryzen');
  assert.strictEqual(s.calls.length, 3);
});

test('an iPhone not on the cable, or a GET nobody asked for, is refused', () => {
  const { h, b } = host();
  b.fire(T.IOS_SCREEN_WANT, { on: true, id: 'ios-usb-2', key: KEY, pull: true }, 'ryzen');
  assert.strictEqual(b.sent.at(-1)[1].on, false);
  const res = sink();
  h.request({ url: PULL, method: 'GET', headers: { [HEADER]: 'cd'.repeat(16) } }, res);
  assert.strictEqual(res.code, 403);
});

test('the viewer sends its window\'s input as ios.input, across the picture', () => {
  const b = bus();
  const r = new RelayScreen({ hub: { bus: b, sessions: new Map() }, host: 'mac', id: 'ios-usb-1' });
  r.touch(7, -1, 10, 10, 750, 1334); // hover: nothing
  r.touch(0, -2, 375, 667, 750, 1334);
  r.touch(1, -2, 375, 667, 750, 1334);
  r.keyCode('KeyB', false);
  r.tap(3);
  assert.deepStrictEqual(b.sent.map(([to, m]) => [to, m.op, m.a ?? m.code ?? m.b, m.x, m.y]), [
    ['mac', 'touch', 0, 0.5, 0.5], ['mac', 'touch', 1, 0.5, 0.5], ['mac', 'key', 'KeyB', undefined, undefined], ['mac', 'button', 3, undefined, undefined],
  ]);
  assert.ok(b.sent.every(([, m]) => m.t === T.IOS_INPUT && m.id === 'ios-usb-1' && m.key === r.secret));
});

test('a source that throws ends that viewer with why, and nothing else', () => {
  const b = bus();
  const done = [];
  new ScreenHost({ hub: { bus: b, sessions: new Map() } }).add({
    find: () => 'DEV',
    use: () => { throw new TypeError('broken'); },
    current: () => null,
    done: (d) => done.push(d),
  });
  assert.doesNotThrow(() => b.fire(T.IOS_SCREEN_WANT, { on: true, id: 'android-1', key: KEY, pull: true }, 'ryzen'));
  assert.deepStrictEqual(b.sent.at(-1), ['ryzen', { t: T.IOS_SCREEN_STATE, key: KEY, on: false, error: 'The phone’s screen couldn’t start here' }]);
  assert.deepStrictEqual(done, ['DEV']);
});