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.

6.0 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Debug of the Android phones connected here (docs/debug.md): a phone isn't a computer of the mesh,
// so a request for one (shared/meshdebug.js: its phone()) is answered by the computer it's connected
// to, on its behalf and under that computer's rules (Debug › Let these devices debug this computer).
// Whichever computer that is: the mesh's routing takes the request there.
//   hello, status   what this computer knows of it: phone.info, its session, wireless debugging
//   files, log      the app's own log (DebugLog.kt: logcat of its process kept in files, rotated),
//                   asked over its session; an app without it (no "debug.log" in its caps) has none
//   shot            its screen through adb, while wireless debugging (or the cable) is up for it
//   the rest        not on a phone
//
//   computer -> phone  phone.dbg {req, op: 'files'}                  | {req, op: 'read', name, from, len}
//   phone -> computer  phone.dbg.res {req, files: [{name, size}]}    | {req, data (base64), size} | {req, error}
'use strict';

const crypto = require('crypto');
const { execFile } = require('child_process');
const P = require('./protocol.js');

const ANSWER_MS = 10000;
const PIECE = 256 * 1024; // what one read asks for (DebugLog.kt's own cap)
const SHOT_MAX = 32 * 1024 * 1024;

function err(code) {
  const e = new Error(code);
  e.code = code;
  return e;
}

// hub: the mesh hub (bus, sessions); phones(): the Android phones connected here, [{id, name, info
// (phone.js: model, maker, release, sdk, battery, charging, app, caps), adb(): {bin, serial} while adb is
// up for it, else null, bridge: {state, message}}]; self(): this computer's name.
function phoneDebug({ hub, phones, self = () => '' }) {
  const pending = new Map(); // req -> {id, resolve, reject, timer}

  hub.bus.on('phone.dbg.res', (m, from) => {
    const p = m && pending.get(String(m.req || ''));
    if (!p || p.id !== from) return;
    pending.delete(m.req);
    clearTimeout(p.timer);
    if (m.error) p.reject(err(String(m.error).slice(0, 200)));
    else p.resolve(m);
  });

  // One question to the app on the phone, over its session.
  const ask = (id, msg) => new Promise((resolve, reject) => {
    const req = crypto.randomBytes(8).toString('hex');
    const timer = setTimeout(() => { pending.delete(req); reject(err('the app on the phone didn’t answer')); }, ANSWER_MS);
    if (timer.unref) timer.unref();
    pending.set(req, { id, resolve, reject, timer });
    if (!hub.bus.send(id, { t: 'phone.dbg', req, ...msg })) {
      pending.delete(req);
      clearTimeout(timer);
      reject(err('unreachable'));
    }
  });

  const no = () => Promise.reject(err('not on a phone'));

  // The tools of the phone `id` connected here (meshdebug.js's local, for that phone), or null.
  return function tools(id) {
    const ph = () => (phones() || []).find((p) => p.id === id) || null;
    if (!ph()) return null;
    const info = () => (ph() || {}).info || {};
    const logs = () => {
      const caps = info().caps;
      if (!Array.isArray(caps) || !caps.includes('debug.log')) throw err('the app on the phone keeps no log: update TwinDesk there');
    };
    return {
      async hello() {
        const p = ph() || {};
        const i = info();
        return {
          name: p.name || '', version: i.app || '', os: P.OS.ANDROID, edition: '', phone: true,
          model: [i.maker, i.model].filter(Boolean).join(' '), release: i.release || '', battery: i.battery ?? null,
          through: self(), // the computer that answers for it
          diagnostics: [], update: { kind: '' },
        };
      },
      async status() {
        const p = ph() || {};
        const i = info();
        const s = hub.sessions.get(id);
        const a = p.adb ? p.adb() : null;
        return {
          phone: { name: p.name, model: i.model, maker: i.maker, release: i.release, sdk: i.sdk, app: i.app, caps: i.caps || [], battery: i.battery, charging: !!i.charging, display: i.display || null },
          through: self(),
          session: s ? { connected: !!s.connected, transport: s.transport || 'ip', rtt: s.rtt ?? null } : null,
          adb: { state: (p.bridge && p.bridge.state) || '', message: (p.bridge && p.bridge.message) || '', serial: a ? a.serial : '' },
        };
      },
      verbose: no,
      async files() {
        logs();
        const r = await ask(id, { op: 'files' });
        return (Array.isArray(r.files) ? r.files : []).slice(0, 10)
          .filter((f) => f && typeof f.name === 'string' && /^TwinDesk\.log(\.\d)?$/.test(f.name))
          .map((f) => ({ name: f.name, size: Math.max(0, Number(f.size) || 0) }));
      },
      // meshdebug.js reads a file without a path through this: in PIECE pieces from the app.
      async read(name, from, len) {
        logs();
        const parts = [];
        for (let at = from, left = len; left > 0;) {
          const r = await ask(id, { op: 'read', name, from: at, len: Math.min(PIECE, left) });
          const b = Buffer.from(String(r.data || ''), 'base64');
          if (!b.length) break;
          parts.push(b);
          at += b.length;
          left -= b.length;
        }
        return Buffer.concat(parts);
      },
      shot() {
        const a = (ph() || {}).adb ? ph().adb() : null;
        if (!a || !a.bin) return Promise.reject(err('no adb: its screen needs wireless debugging (or the cable) up'));
        return new Promise((resolve, reject) => {
          execFile(a.bin, ['-s', a.serial, 'exec-out', 'screencap', '-p'], { encoding: 'buffer', timeout: 15000, maxBuffer: SHOT_MAX }, (e, out) => {
            if (e || !out || out.length < 8 || out.readUInt32BE(0) !== 0x89504e47) return reject(err(`screencap failed${e ? `: ${e.message}` : ''}`.slice(0, 200)));
            resolve({ data: { display: 0, of: 1, tool: 'adb screencap' }, bin: out });
          });
        });
      },
      diag: no,
      run: no,
      restart: no,
      put: no,
      update: no,
    };
  };
}

module.exports = { phoneDebug };