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.

20.9 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Files dropped onto Monitor 2 → the Mac, and files and
// folders dragged across the edge (`drag.start` + `file.offer {drop:'drag', rel}`, the
// Mac shows a real drag and the drop target pulls the data): one file at a time over the control
// channel in base64 chunks, with a SHA-256 check. Waits while the socket is backed up so mouse and
// keyboard messages never sit behind a big file. Send files and pastes the other side
// asked for go the same way as batches (`drop:'send'|'paste'`, `batch`, `rel`), ended by `files.done`.
// With an app that can, on the network or a cable, the bytes go over HTTPS instead, up to four files
// at once (shared/fastfile.js, link.fx; in Multi-device the selected device's, shared/meshfx.js).
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const P = require('../shared/protocol.js');
const awake = require('../shared/awake.js');
const { Outbox } = require('../shared/outbox.js');

const T = P.T;
const HIGH_WATER = 1024 * 1024;
const MAX_DRAG_FILES = 10000; // pause sending chunks above this many queued bytes
const ANSWER_MS = 15000; // offer → accept/refuse
// … through Bluetooth: the offer waits for Wi-Fi first (netlink.js holdOut, up to its 60 s
// ASK_TIMEOUT_MS, then it goes through Bluetooth), so the answer can't come before that.
const ANSWER_BLE_MS = 90000;
const DONE_MS = 120000; // end → done (the Mac hashes and moves the file)

class FileDrop {
  // opts: link, settings (shared), onProgress(view)
  constructor(opts) {
    Object.assign(this, opts);
    this.queue = [];
    this.sending = 0; // jobs being sent (one, or a few with fast files)
    this.active = new Map(); // id → {id, name, size, sent, index, count, …} being sent
    this.current = null; // the newest of them, for the view
    this.last = null; // {name, ok, text}
    this.sent = []; // newest first; Activity lists finished sends. No path: reveal is received files only.
    this.waiters = new Map(); // id → {resolve, types}
    for (const t of [T.FILE_ACCEPT, T.FILE_REFUSE, T.FILE_DONE, T.FILE_CANCEL]) this.link.on(t, (m) => this._answer(m));
    this.drag = null; // {drag, name} while a drag's files are being sent
    this.link.on(T.DRAG_END, (m) => this._dragEnd(m));
    this.batches = new Map(); // Batch → {kind, name, files, bytes}
    this.link.on(T.FILES_DONE, (m) => this._batchDone(m));
    // Files › Send files waiting for the other device: sent while away, paused, cut off (shared/outbox.js).
    // opts.peer() → {id, name} of the device connected now; opts.outboxFile.
    const peerNow = () => (this.link.status && this.link.status.state === 'connected' && this.peer ? this.peer() : null);
    // opts.outbox: given in Multi-device, each device's FileDrop a view of one list (shared/filedrop-mesh.js).
    if (!this.outbox) this.outbox = new Outbox({
      file: this.outboxFile || null,
      hours: () => ((this.settings && this.settings.files) || {}).outboxHours,
      // Before any session since an update: the computer this one is paired with.
      paired: () => { const p = this.link && this.link.snapshot && this.link.snapshot().paired; return p ? { id: p.macId, name: p.macName } : null; },
      peer: peerNow,
      send: (e) => !!this.link.status && this.link.status.state === 'connected' && !!(e.list ? this.sendList(e.list, 'send', crypto.randomUUID(), { cont: e.cont, name: e.name }) : this.sendBatch(e.paths, 'send')),
    });
    this.outbox.on('change', () => this._progress());
    this.link.on('welcome', () => setImmediate(() => this.outbox.connected()));
    this.link.on('closed', () => {
      // Send files cut off: what hadn't arrived goes again when the device is back.
      for (const [batch, b] of [...this.batches]) if (b.kind === 'send' && this._keepRest(batch, 'cut', this.lastPeer)) this.batches.delete(batch);
      this._abortAll('{Name} disconnected');
      for (const batch of [...this.batches.keys()]) this._batchDone({ batch, ok: false });
    });
  }

  // Send files to this link's device: its pair's switch (opts.sends, shared/consent.js), else the settings'.
  _sends() {
    return this.sends ? !!this.sends() : !!this.settings.files.dropToMac;
  }

  // paths from the Monitor 2 drop (x/y normalized over the video, or null), or from a drag across
  // the edge (release = true: the Mac places them where its pointer is when the button comes up).
  drop(paths, x, y, release) {
    if (!this._sends()) return this._report(null, false, 'Dropping files onto Monitor 2 is off (Files tab)', 'Dropping files onto Monitor 2 is off (Files tab)');
    const files = [];
    for (const p of paths) {
      try {
        const st = fs.statSync(p);
        if (st.isFile()) files.push({ path: p, size: st.size });
      } catch (_) { /* gone */ }
    }
    if (!files.length) return this._report(null, false, 'Only files can be sent (not folders)', 'Only files can be sent (not folders)');
    files.forEach((f, i) => this.queue.push({ ...f, x, y, release: !!release, index: i, count: files.length }));
    this._next();
  }

  // A drag across the edge: walk the folders. Returns what kvm.take and
  // beginDrag need, or null when nothing can go. Nothing is sent yet: kvm.take goes first.
  prepareDrag(paths) {
    if (!this._sends() || this.link.status.state !== 'connected') return null;
    const d = plan(paths);
    return d && { drag: crypto.randomBytes(8).toString('hex'), ...d, count: d.items.length };
  }

  // Send files (kind 'send') or a paste the other side asked for (kind 'paste', batch =
  // the fclip id): every file offered in order with its folder path. Returns the plan, or null.
  sendBatch(paths, kind, batch = crypto.randomUUID()) {
    if (this.link.status.state !== 'connected') return null;
    const d = plan(paths);
    if (!d || !d.jobs.length) return null;
    const name = d.items.length === 1 ? d.items[0].name : d.items.length + ' items';
    return { ...this._queueAll(d.jobs, kind, batch, { name, itemCount: d.items.length }), items: d.items };
  }

  // The rest of a batch (shared/outbox.js): jobs [{path, rel, size}] as planned, sizes read again.
  // cont: the first batch's id, so the receiver puts them into the same folders.
  sendList(list, kind, batch, { cont, name } = {}) {
    if (this.link.status.state !== 'connected' || this.batches.has(batch)) return null;
    const jobs = [];
    for (const f of list) {
      try { const st = fs.statSync(f.path); if (st.isFile() && st.size <= P.FILE_MAX_BYTES) jobs.push({ path: f.path, rel: f.rel, size: st.size }); } catch (_) { /* gone */ }
    }
    if (!jobs.length) return null;
    const tops = new Set(jobs.map((j) => j.rel.split('/')[0]));
    return this._queueAll(jobs, kind, batch, { name: name || (tops.size === 1 ? [...tops][0] : tops.size + ' items'), itemCount: tops.size, cont });
  }

  _queueAll(jobs, kind, batch, { name, itemCount, cont }) {
    const bytes = jobs.reduce((s, j) => s + j.size, 0);
    this.batches.set(batch, { kind, name, itemCount, files: jobs.length, bytes, sent: 0, jobs, arrived: new Set(), cont });
    if (this.peer) this.lastPeer = this.peer();
    jobs.forEach((j, i) => this.queue.push({ ...j, batch, kind, index: i, count: jobs.length }));
    this._progress();
    this._next();
    return { batch, name, files: jobs.length, bytes };
  }

  // Files › Send files: now, or kept for the device last connected (shared/outbox.js).
  send(paths) {
    return this.outbox.add(paths);
  }

  // Pause on a batch on its way: the files on their way stop, the rest waits for Resume.
  pause(batch) {
    const b = this.batches.get(batch);
    if (!b || b.kind !== 'send') return false;
    this._keepRest(batch, 'paused', this.peer ? this.peer() : null);
    this.batches.delete(batch);
    this.queue = this.queue.filter((j) => j.batch !== batch);
    for (const c of [...this.active.values()]) {
      if (c.batch !== batch) continue;
      this.link.send({ t: T.FILE_CANCEL, id: c.id, pause: true });
      const w = this.waiters.get(c.id);
      this.active.delete(c.id);
      if (this.link.fx) this.link.fx.cancel(c.id);
      if (w) w.reject(localError('Cancelled'));
    }
    this.current = [...this.active.values()].pop() || null;
    this._progress();
    return true;
  }

  resume(id) { return this.outbox.resume(id); }
  forget(id) { this.outbox.remove(id); }

  _keepRest(batch, why, peer) {
    const b = this.batches.get(batch);
    if (!b || !b.jobs) return null;
    const rest = b.jobs.filter((j) => !b.arrived.has(j.rel)).map((j) => ({ path: j.path, rel: j.rel, size: j.size }));
    return this.outbox.keep(rest, { why, cont: b.cont || batch, name: b.name, peer });
  }

  // What a set of paths would send (fclip.js announces it before anything is sent).
  plan(paths) {
    return plan(paths);
  }

  _batchDone(m) {
    const b = this.batches.get(m.batch);
    if (!b) return;
    this.batches.delete(m.batch);
    this.queue = this.queue.filter((j) => j.batch !== m.batch);
    if (this.onBatchProgress) this.onBatchProgress({ ...b, done: true, ok: !!m.ok });
    const folder = typeof m.where === 'string' ? m.where.slice(0, 300) : '';
    this._report(b.name, !!m.ok, m.ok ? 'Sent' + (folder ? ' to ' + folder : '') : 'Not everything arrived',
      m.ok ? (folder ? 'Sent to {folder}' : 'Sent') : 'Not everything arrived', folder ? { folder } : {}, b.itemCount);
  }

  // Right after kvm.take: describe everything in `drag.start`, then send the files.
  beginDrag(d) {
    this.cancelRelease(); // one drag at a time
    const { drag, items, dirs, list, jobs, bytes } = d;
    this.drag = { drag, name: items.length > 1 ? items.length + ' items' : items[0].name, itemCount: items.length };
    this.link.send({ t: T.DRAG_START, drag, items, dirs, list, files: list.length, bytes });
    jobs.forEach((j, i) => this.queue.push({ ...j, drag, index: i, count: jobs.length }));
    this._next();
  }

  // The Mac says how the drag ended: dropped (show where), or cancelled — stop sending.
  _dragEnd(m) {
    if (!this.drag || m.drag !== this.drag.drag) return;
    const d = this.drag;
    this.drag = null;
    console.log('[drag] out, ' + m.result + (typeof m.where === 'string' && m.where ? ' in ' + m.where.slice(0, 200) : '') + ' (' + d.name + ')');
    if (m.result === 'dropped') {
      const folder = typeof m.where === 'string' ? m.where : '';
      this._report(d.name, true, 'Dropped on {name}' + (folder ? ' in ' + folder : ''),
        folder ? 'Dropped on {name} in {folder}' : 'Dropped on {name}', folder ? { folder } : {}, d.itemCount);
    }
    else {
      this._stopDrag(d.drag, false);
      const message = m.result === 'failed' ? '{Name} couldn’t take the drag' : 'Drag cancelled';
      this._report(d.name, false, message, message, {}, d.itemCount);
    }
  }

  _stopDrag(drag, tellMac) {
    if (tellMac) this.link.send({ t: T.DRAG_CANCEL, drag });
    this.queue = this.queue.filter((j) => j.drag !== drag);
    if ([...this.active.values()].some((c) => c.drag === drag)) this.cancel();
  }

  _next() {
    const fx = this.link.fx;
    while (this.queue.length && this.sending < (fx ? fx.parallelFor(this.queue[0].size) : 1)) {
      const job = this.queue.shift();
      this.sending++;
      this._run(job).finally(() => {
        this.sending--;
        this._next();
      });
    }
  }

  async _run(job) {
    try {
      await this._send(job);
    } catch (e) {
      if (!job.batch) this._report(path.basename(job.path), false, e.message, e.messageKey, e.messageVars);
      else if (e.refused === 'not_allowed' && this.batches.has(job.batch)) { // turned off over there: the rest won't go either
        const b = this.batches.get(job.batch);
        this.batches.delete(job.batch);
        this.queue = this.queue.filter((j) => j.batch !== job.batch);
        this._report(b.name, false, e.message, e.messageKey, e.messageVars, b.itemCount);
      } // other failures: files.done says how the batch went
    }
  }

  async _send(job) {
    const name = path.basename(job.path);
    if (this.link.status.state !== 'connected') throw localError('Not connected to {name}');
    if (job.size > P.FILE_MAX_BYTES) throw localError('Too big');
    const id = crypto.randomBytes(8).toString('hex');
    const cur = { id, name, size: job.size, sent: 0, index: job.index, count: job.count, release: job.release, drag: job.drag, batch: job.batch };
    this.current = cur;
    this.active.set(id, cur);
    try {
      await this._sendFile(job, cur);
    } finally {
      this.active.delete(id);
      if (this.current === cur) this.current = [...this.active.values()].pop() || null;
    }
  }

  async _sendFile(job, cur) {
    const { id, name } = cur;
    this._progress();
    const offer = { t: T.FILE_OFFER, id, name, size: job.size, index: job.index, count: job.count };
    if (job.drag) Object.assign(offer, { drop: 'drag', drag: job.drag, rel: job.rel });
    else if (job.batch) {
      const b = this.batches.get(job.batch) || {};
      Object.assign(offer, { drop: job.kind, batch: job.batch, rel: job.rel, bytes: b.bytes, ...(b.cont ? { cont: b.cont } : {}) }); // bytes: the batch, for the receiver's progress
    }
    else if (job.release) offer.drop = 'release';
    else { offer.drop = 'point'; if (typeof job.x === 'number') { offer.x = job.x; offer.y = job.y; } }
    this.link.send(offer);
    const c = this.link.current;
    const a = await this._wait(id, [T.FILE_ACCEPT, T.FILE_REFUSE, T.FILE_CANCEL], c && c.transport === 'ble' ? ANSWER_BLE_MS : ANSWER_MS);
    if (a.t !== T.FILE_ACCEPT) {
      const e = localError(a.t === T.FILE_REFUSE ? refuseText(a.why) : 'Cancelled');
      e.refused = a.t === T.FILE_REFUSE ? a.why : '';
      throw e;
    }

    const sha256 = (await this._fast(job, cur)) || (await this._chunks(job, cur));
    this.link.send({ t: T.FILE_END, id, sha256, ...(this.link.fx ? this.link.fx.endFields(id) : {}) }); // fx2: the ranges' hashes
    if (job.drag) return; // the Mac answers file.done when the drop target has it; drag.end says how it went
    const d = await this._wait(id, [T.FILE_DONE, T.FILE_CANCEL], DONE_MS);
    if (d.t !== T.FILE_DONE || !d.ok) throw d.error ? new Error(d.error) : localError('{Name} couldn’t save it');
    if (job.batch) { // listed once, on files.done
      const b = this.batches.get(job.batch);
      if (b && b.arrived) b.arrived.add(job.rel);
      return;
    }
    this._report(name, true, d.path ? 'Saved on {name}: ' + d.path : 'Saved on {name}',
      d.path ? 'Saved on {name}: {path}' : 'Saved on {name}', d.path ? { path: d.path } : {});
  }

  // Fast files: the SHA-256 once it went, or null to send it the old way (an older app, Bluetooth, a
  // Wi-Fi link netlink made, or it didn't work before any byte went).
  async _fast(job, cur) {
    const fx = this.link.fx;
    if (!fx || !fx.usable()) return null;
    let shown = 0;
    try {
      return await fx.send(cur.id, job.path, job.size, (n) => {
        const now = Date.now();
        this._sent(job, cur, n, now - shown >= 100);
        if (now - shown >= 100) shown = now;
      });
    } catch (e) {
      if (this.active.get(cur.id) !== cur) throw localError('Cancelled');
      if (!e.early) {
        this.link.send({ t: T.FILE_CANCEL, id: cur.id });
        throw e;
      }
      console.log('[files] fast files didn’t work (' + e.message + '): sending the usual way');
      return null;
    }
  }

  // The usual way: base64 file.chunk messages on the session's socket. Returns the SHA-256.
  async _chunks(job, cur) {
    const id = cur.id;
    const hash = crypto.createHash('sha256');
    let seq = 0;
    const stream = fs.createReadStream(job.path, { highWaterMark: P.FILE_CHUNK_BYTES });
    try {
      for await (const chunk of stream) {
        if (this.active.get(id) !== cur) throw localError('Cancelled');
        while (this.link.bufferedAmount > HIGH_WATER) await sleep(15);
        if (this.link.status.state !== 'connected') throw localError('{Name} disconnected');
        hash.update(chunk);
        this.link.send({ t: T.FILE_CHUNK, id, seq: seq++, data: chunk.toString('base64') });
        awake.touch(); // stay awake while the bytes go (shared/awake.js)
        this._sent(job, cur, chunk.length, true);
      }
    } finally {
      stream.destroy();
    }
    return hash.digest('hex');
  }

  _sent(job, cur, n, show) {
    cur.sent += n;
    const b = job.batch && this.batches.get(job.batch);
    if (b) b.sent += n;
    if (!show) return;
    if (b && this.onBatchProgress) this.onBatchProgress(b); // The popup for big batches
    this._progress();
  }

  _wait(id, types, ms) {
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => { this.waiters.delete(id); reject(localError('{Name} didn’t answer')); }, ms);
      this.waiters.set(id, { types, resolve: (m) => { clearTimeout(timer); this.waiters.delete(id); resolve(m); }, reject: (e) => { clearTimeout(timer); this.waiters.delete(id); reject(e); } });
    });
  }

  _answer(m) {
    const c = this.active.get(m.id);
    if (m.t === T.FILE_CANCEL && c) c.cancelled = true;
    const w = this.waiters.get(m.id);
    if (w && w.types.includes(m.t)) w.resolve(m);
  }

  // Input went home before the button came up: the dragged files don't go, and a
  // Drag is cancelled on the Mac.
  cancelRelease() {
    this.queue = this.queue.filter((j) => !j.release);
    if ([...this.active.values()].some((c) => c.release)) this.cancel();
    if (this.drag) {
      const d = this.drag;
      this.drag = null;
      this._stopDrag(d.drag, true);
    }
  }

  // Stop what's being sent (with fast files, every file in flight).
  cancel() {
    if (!this.active.size) return;
    let all = false;
    for (const c of [...this.active.values()]) {
      this.link.send({ t: T.FILE_CANCEL, id: c.id });
      const w = this.waiters.get(c.id);
      const b = c.batch && this.batches.get(c.batch);
      if (b) {
        this.batches.delete(c.batch);
        this._report(b.name, false, 'Cancelled', 'Cancelled', {}, b.itemCount);
      }
      if (!c.drag) all = true;
      this.active.delete(c.id); // the chunk loop stops at its next check
      if (this.link.fx) this.link.fx.cancel(c.id);
      if (w) w.reject(localError('Cancelled'));
    }
    if (all) this.queue = [];
    this.current = null;
  }

  _abortAll(why) {
    this.queue = [];
    for (const w of [...this.waiters.values()]) w.reject(localError(why));
  }

  _progress() {
    this.onProgress(this.view());
  }

  _report(name, ok, text, messageKey, messageVars = {}, itemCount) {
    this.last = { name, ok, text, at: Date.now(), ...(messageKey ? { messageKey, messageVars } : {}), ...(itemCount > 1 ? { itemCount } : {}) };
    if (typeof name === 'string' && name) {
      const files = itemCount > 1 ? itemCount : 0;
      this.sent.unshift({ name, ok: !!ok, at: this.last.at, ...(files > 1 ? { files } : {}) });
      if (this.sent.length > 20) this.sent.length = 20;
    }
    this.onProgress(this.view());
  }

  view() {
    const c = this.current;
    const b = c && c.batch && this.batches.get(c.batch);
    return {
      current: c ? { name: c.name, size: c.size, sent: c.sent, index: c.index, count: c.count } : null,
      // The Send files / paste batch being sent, for the Files tab's progress bar
      batch: b ? { id: c.batch, name: b.name, files: b.files, index: c.index, bytes: b.bytes, sent: b.sent, kind: b.kind } : null,
      queued: this.queue.length,
      outbox: this.outbox.view,
      outboxPeer: this.outbox.last ? this.outbox.last.name : '',
      sent: this.sent,
      last: this.last,
    };
  }
}

// Walk the paths (folders too): what drag.start and the batches need. Symbolic links are skipped.
function plan(paths) {
  const items = [], dirs = [], list = [], jobs = [];
  let bytes = 0;
  const walk = (abs, rel) => {
    let st;
    try { st = fs.lstatSync(abs); } catch (_) { return; }
    if (st.isSymbolicLink()) return;
    if (st.isDirectory()) {
      dirs.push(rel);
      let names = [];
      try { names = fs.readdirSync(abs); } catch (_) { /* unreadable: sent empty */ }
      for (const n of names.sort()) { if (list.length >= MAX_DRAG_FILES) return; walk(path.join(abs, n), rel + '/' + n); }
    } else if (st.isFile() && st.size <= P.FILE_MAX_BYTES && list.length < MAX_DRAG_FILES) {
      list.push({ rel, size: st.size });
      jobs.push({ path: abs, size: st.size, rel });
      bytes += st.size;
    }
  };
  for (const p of paths) {
    const name = path.basename(p);
    const before = bytes;
    let dir = false;
    try { dir = fs.lstatSync(p).isDirectory(); } catch (_) { continue; }
    walk(p, name);
    items.push({ name, dir, size: bytes - before });
  }
  if (!items.length) return null;
  return { items, dirs, list, jobs, bytes };
}

function refuseText(why) {
  return { not_allowed: '{Name} doesn’t accept dropped files (its Files tab)', too_big: 'Too big for {name}', busy: '{Name} is busy with another file' }[why] || '{Name} refused it';
}

// Local presentation metadata; the legacy message and file protocol stay unchanged.
function localError(message) {
  return Object.assign(new Error(message), { messageKey: message });
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

module.exports = FileDrop;