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.

19.7 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Mesh managers (shared/mesh-mgr.js) and Biometric unlock from this computer (shared/unlock-client.js):
//   MeshManagers.create()   the card at the bottom of Multi-device. Every edition: a manager asking to add
//     this computer (Accept, Decline) and who manages it (Revoke). Mesh manager mode: TwinDesk Professional or a
//     Mac, turned on after a warning (grayed out in the standard build, with where to get Pro); then every
//     other computer to add, each asked on its own screen, and under each its Biometric unlock (off; only a
//     TwinDesk Professional computer; that computer accepts the risk). state.mgr
//   UnlockPeers.create({ on(v), unlock(id) })   Unlock other computers: the switch and the computers this one
//     may unlock (Touch ID on a Mac, Windows Hello). state.unlocker. One-to-one: on Overview
//   The Mesh manager page: only while Mesh manager mode is on (state.mgr.on): the computers that
//     accepted it, Lock, Sleep, Restart, Shut down, Wake, Unlock, and Unlock all.
'use strict';

(function () {
  const t = (k, v) => I18n.t(k, v);
  const WHY = {
    off: 'Mesh managers are off there', revoked: 'Not accepted there, or revoked', notmgr: 'This computer isn’t a mesh manager',
    cant: 'It can’t do that', nothing: 'Nothing to do', timeout: 'It didn’t answer', offline: 'Not connected', unknown: 'An older TwinDesk there',
  };
  const literal = { literal: true };

  // Styles: .mgr-gray, .mgr-sub-row, .mgr-sub in each app's stylesheet (no inline styles: the Mac's CSP).

  // A centred warning with Cancel and a confirm button (as turning on Multi-device asks: shared/mesh-intro.js).
  function warn({ title, lines, ok, danger }, onOk) {
    const el = (tag, cls, text) => {
      const e = document.createElement(tag);
      if (cls) e.className = cls;
      if (text) e.textContent = text;
      return e;
    };
    const pop = el('div', 'pair-pop mesh-pop');
    pop.setAttribute('role', 'dialog');
    pop.setAttribute('aria-modal', 'true');
    const body = el('div', 'pop-body');
    body.append(el('strong', '', title), ...lines.map((l, i) => el(i === lines.length - 1 && lines.length > 1 ? 'div' : 'p', i === lines.length - 1 && lines.length > 1 ? 'hint' : '', l)));
    const cancel = el('button', 'btn', t('Cancel'));
    const yes = el('button', danger ? 'btn danger' : 'btn primary', ok);
    const actions = el('div', 'banner-actions');
    actions.append(cancel, yes);
    pop.append(body, actions);
    const close = () => { document.removeEventListener('keydown', onKey, true); pop.remove(); };
    function onKey(e) { if (e.key === 'Escape') close(); }
    cancel.onclick = close;
    yes.onclick = () => { close(); onOk(); };
    document.addEventListener('keydown', onKey, true);
    document.body.append(pop);
    cancel.focus(); // the safe answer first
  }

  const named = (row) => { row.dataset.literal = ''; return row; };

  function managers() {
    const { api } = UI;
    const set = (o) => api.setMgr && api.setMgr(o);
    const el = UI.el('div', { class: 'mgr-list' });
    const card = UI.card(t('Mesh managers'), [el]);
    const open = new Set(); // computers shown expanded
    let lastKey = '';
    let last = null;

    function turnOn() {
      warn({
        title: t('Make this computer a mesh manager?'),
        lines: [
          t('It can then lock, sleep, restart and shut down the computers you add, and unlock those that allow it. Each computer is added only when someone accepts on that computer.'),
          t('Use it only with computers you own. Turning it off lets every computer go.'),
        ],
        ok: t('Turn on'),
      }, () => set({ on: true }));
    }

    function accept(a, perm) {
      if (perm === 'power') {
        return warn({
          title: t('Let {computer} manage this computer?', { computer: a.name }),
          lines: [t('{computer} can then lock, sleep, restart and shut down this computer. You can revoke it here any time.', { computer: a.name })],
          ok: t('Accept'),
        }, () => set({ answer: { mgr: a.id, perm, yes: true } }));
      }
      warn({
        title: t('Let {computer} unlock this computer?', { computer: a.name }),
        lines: [
          t('Whoever can sign in on {computer} with Windows Hello or Touch ID can then open this computer’s lock screen without its password.', { computer: a.name }),
          t('Then add {computer} under Biometric unlock on this computer.', { computer: a.name }),
        ],
        ok: t('Accept the risk'),
        danger: true,
      }, () => set({ answer: { mgr: a.id, perm, yes: true } }));
    }

    const STATE = { accepted: 'Added', offered: 'Waiting for it to accept', '': 'Not added' };
    const USTATE = { accepted: 'On: it accepted', offered: 'Waiting for it to accept the risk', '': 'Off' };

    function render(m) {
      last = m;
      card.hidden = !m;
      if (!m) return;
      const key = JSON.stringify([m, [...open]]);
      if (key === lastKey) return;
      lastKey = key;
      const rows = [];

      // Managed here (every edition).
      for (const a of m.asks || []) {
        for (const p of a.perms) {
          rows.push(named(UI.row(p === 'power' ? t('{computer} asks to manage this computer', { computer: a.name }) : t('{computer} asks to unlock this computer', { computer: a.name }),
            p === 'power' ? t('Lock, sleep, restart and shut down') : t('With Windows Hello or Touch ID, without this computer’s password'), [
              UI.button(t('Accept'), () => accept(a, p), 'small primary'),
              UI.button(t('Decline'), () => set({ answer: { mgr: a.id, perm: p, yes: false } }), 'small'),
            ], literal)));
        }
      }
      for (const g of m.grants || []) {
        rows.push(named(UI.row(t('Managed by {computer}', { computer: g.name }), g.perms.map((p) => (p === 'power' ? t('Power') : t('Biometric unlock'))).join(', '),
          [UI.button(t('Revoke'), () => set({ revoke: g.id }), 'small')], literal)));
      }

      // Mesh manager mode.
      if (!m.canManage) {
        const r = UI.row(t('Mesh manager mode'), t('Make this computer the admin device of the mesh: lock, restart, shut down and unlock the others that accept it. Download TwinDesk Professional (free) to use it.'),
          [UI.button(t('Get TwinDesk Professional (free)'), () => api.openLink && api.openLink('releases'), 'small')]);
        r.classList.add('mgr-gray');
        rows.push(r);
      } else if (!m.on) {
        const r = UI.row(t('Mesh manager mode'), t('Off. Make this computer the admin device of the mesh: it locks, restarts, shuts down and unlocks the computers that accept it'),
          [UI.button(t('Turn on'), turnOn, 'small primary')]);
        r.classList.add('mgr-gray');
        rows.push(r);
      } else {
        rows.push(UI.row(t('Mesh manager mode'), t('On. Add computers below; each one accepts on its own screen'), [UI.button(t('Turn off'), () => set({ on: false }), 'small')]));
        for (const d of m.computers || []) {
          const sw = UI.switch((v) => set({ pick: { id: d.id, on: v } }), { label: t('Add {computer}', { computer: d.name }) });
          sw.set(d.picked);
          const status = !d.online ? t('Not connected') : !d.said ? t('An older TwinDesk there') : d.picked ? t(STATE[d.power]) : t('Not added');
          const more = UI.button(open.has(d.id) ? '▾' : '▸', () => { if (open.has(d.id)) open.delete(d.id); else open.add(d.id); lastKey = ''; render(last); }, 'small');
          more.setAttribute('aria-label', t('Options for {computer}', { computer: d.name }));
          more.disabled = !d.picked;
          rows.push(named(UI.row(d.name, status, [more, sw], literal)));
          if (d.picked && open.has(d.id)) {
            const usw = UI.switch((v) => set({ unlock: { id: d.id, on: v } }), { label: t('Biometric unlock') });
            usw.set(d.wantUnlock);
            const ok = d.pro && d.power === 'accepted';
            usw.disable(!ok && !d.wantUnlock);
            const hint = !d.pro ? t('Only a computer running TwinDesk Professional (free) can be unlocked')
              : d.power !== 'accepted' ? t('Once {computer} accepted this manager', { computer: d.name })
                : t(USTATE[d.unlock]);
            const r = named(UI.row(t('Biometric unlock'), hint, [usw], literal));
            r.classList.add('mgr-sub-row');
            if (!ok) r.classList.add('mgr-gray');
            rows.push(r);
          }
        }
        if (!(m.computers || []).length) rows.push(UI.row(t('No other computer yet'), '', []));
      }
      el.replaceChildren(...rows);
    }
    return { el: card, render };
  }

  function unlockPeers(opts) {
    const el = UI.el('div', { class: 'unlock-peers' });
    const sw = UI.switch((v) => opts.on(v), { label: t('Unlock other computers') });
    const head = UI.row(t('Unlock other computers'), '', [sw]);
    const list = UI.el('div');
    const note = UI.note('info', '');
    el.append(head, list, note);
    function render(u) {
      if (!u) { el.hidden = true; return; }
      el.hidden = false;
      const how = u.kind === 'hello' ? t('Windows Hello') : t('Touch ID');
      sw.set(!!u.on);
      sw.disable(!u.can && !u.on);
      head.setHint(!u.can ? (u.kind === 'hello' ? t('Set up Windows Hello on this PC first') : t('Set up Touch ID on this Mac first'))
        : u.on ? t('{how} unlocks TwinDesk Professional computers that allow it. Add this computer from their Biometric unlock page', { how })
          : t('Off: other computers can’t ask this one to unlock them'));
      const rows = [];
      if (u.on && !opts.noList) {
        for (const c of u.targets || []) {
          const status = !c.set ? (c.on ? t('Not added yet: add this computer from its Biometric unlock page') : (c.off ? t(c.off) : t('No Biometric unlock there')))
            : !c.on ? t(c.off || 'Not available right now') : c.locked ? t('Locked') : t('Unlocked');
          const b = UI.button(t('Unlock'), () => opts.unlock(c.id), 'small');
          b.disabled = !(c.set && c.on && c.locked) || !!u.busy;
          rows.push(named(UI.row(c.name, status, c.set ? [b] : [], literal)));
        }
      }
      list.replaceChildren(...rows);
      note.set(u.busy ? t('Confirm with {how}…', { how }) : (u.note ? t(u.note) : ''));
    }
    return { el, render };
  }

  // Power actions of the Mesh manager (shared/mesh-mgr.js act): Restart and Shut down ask first.
  function act(d, what, label) {
    const go = () => UI.api.setMgr && UI.api.setMgr({ act: { to: d.id, do: what } });
    if (what !== 'restart' && what !== 'shutdown') return go();
    warn({
      title: t('{action} {computer}?', { action: label, computer: d.name }),
      lines: [t('Anything open on {computer} that isn’t saved may be lost.', { computer: d.name })],
      ok: label, danger: true,
    }, go);
  }

  // A computer's Unlock (Windows Hello or Touch ID) and what is still missing until it can: the button is
  // always there, enabled only while it's ready and that computer is locked. d: a mgr.computers entry,
  // u: state.unlocker, x: its unlock target. → { hint, btns, ready }
  function unlockLine(d, u, x) {
    const { api } = UI;
    const set = (o) => api.setMgr && api.setMgr(o);
    const id = d.id;
    const how = u && u.kind === 'hello' ? t('Windows Hello') : t('Touch ID');
    const unlock = UI.button(t('Unlock'), () => api.unlocker && api.unlocker('unlock', id), 'small primary');
    const ready = d.unlock === 'accepted' && x && x.set && x.on;
    unlock.disabled = !(ready && x.locked) || !!(u && u.busy);
    const btns = [unlock];
    let hint;
    if (!d.pro) hint = t('Only a computer running TwinDesk Professional (free) can be unlocked');
    else if (d.power !== 'accepted') hint = t('Once {computer} accepted this manager', { computer: d.name });
    else if (!d.wantUnlock) {
      hint = t('Off. Turn it on, then {computer} accepts the risk on its own screen', { computer: d.name });
      btns.unshift(UI.button(t('Turn on'), () => set({ unlock: { id, on: true } }), 'small'));
    } else if (d.unlock !== 'accepted') hint = t('Waiting for it to accept the risk');
    else if (!u) hint = t('This computer can’t confirm with Windows Hello or Touch ID');
    else if (!u.on) {
      hint = !u.can ? (u.kind === 'hello' ? t('Set up Windows Hello on this PC first') : t('Set up Touch ID on this Mac first'))
        : t('Turn on Unlock other computers to confirm with {how}', { how });
      if (u.can) btns.unshift(UI.button(t('Turn on'), () => api.unlocker('on', true), 'small'));
    } else if (!x || !x.set) hint = t('Add this computer on {computer}: Biometric unlock › Add a device', { computer: d.name });
    else if (!x.on) hint = t(x.off || 'Not available right now');
    else if (u.busy === id) hint = t('Confirm with {how}…', { how });
    else hint = x.locked ? t('Locked. Unlock confirms with {how}', { how }) : t('Unlocked');
    return { hint, btns, ready };
  }

  // One computer's part on its Overview (shared/ui-device-pc.js), while this computer is a mesh manager:
  // added or not, its power actions, and Unlock with Windows Hello or Touch ID, always listed with
  // what is still missing when it can't unlock yet. render(s, id) → hidden when manager mode is off.
  function forDevice() {
    const { api } = UI;
    const set = (o) => api.setMgr && api.setMgr(o);
    const list = UI.el('div', { class: 'mgr-list' });
    const result = UI.note('warn', '');
    const card = UI.card(t('Mesh manager'), [list, result], { actions: [UI.button(t('All computers'), () => UI.go('meshmgr'), 'small link')] });
    let lastKey = '';
    function render(s, id) {
      const mg = (s && s.mgr) || null;
      const d = mg && mg.on && id ? (mg.computers || []).find((x) => x.id === id) : null;
      card.hidden = !d;
      if (!d) { lastKey = ''; return; }
      const u = s.unlocker || null;
      const x = u && u.on ? (u.targets || []).find((c) => c.id === id) || null : null;
      result.set(mg.result ? t(WHY[mg.result] || mg.result) : '');
      const key = JSON.stringify([d, u && { on: u.on, can: u.can, kind: u.kind, busy: u.busy }, x]);
      if (key === lastKey) return;
      lastKey = key;
      const rows = [];

      // Added to this manager (power): Lock, Sleep, Restart, Shut down, Wake.
      const sw = UI.switch((v) => set({ pick: { id, on: v } }), { label: t('Add {computer}', { computer: d.name }) });
      sw.set(d.picked);
      const status = !d.online ? t('Not connected') : !d.said ? t('An older TwinDesk there')
        : !d.picked ? t('Not added. Add it here; it accepts on its own screen')
          : d.power === 'accepted' ? (d.direct ? t('Added') : t('Connected through another computer: connect it to this one directly'))
            : t('Waiting for it to accept');
      rows.push(named(UI.row(t('Managed by this computer'), status, [sw], literal)));
      if (d.power === 'accepted') {
        const can = d.can || {};
        const acts = [];
        if (d.wake) acts.push(UI.button(t('Wake'), () => act(d, 'wake'), 'small'));
        if (can.lock) acts.push(UI.button(t('Lock'), () => act(d, 'lock'), 'small'));
        if (can.sleep) acts.push(UI.button(t('Sleep'), () => act(d, 'sleep'), 'small'));
        if (can.restart) acts.push(UI.button(t('Restart'), () => act(d, 'restart', t('Restart')), 'small'));
        if (can.shutdown) acts.push(UI.button(t('Shut down'), () => act(d, 'shutdown', t('Shut down')), 'small'));
        if (acts.length) rows.push(UI.row(t('Power'), '', acts));
      }

      // Biometric unlock: the Unlock button is always here; while it can't unlock, the hint says what's missing.
      const { hint, btns, ready } = unlockLine(d, u, x);
      const r = named(UI.row(t('Biometric unlock'), hint, btns, literal));
      if (!ready) r.classList.add('mgr-gray');
      rows.push(r);
      list.replaceChildren(...rows);
    }
    return { el: card, render };
  }

  window.MeshManagers = { create: managers, forDevice };
  window.UnlockPeers = { create: unlockPeers };
  window.MeshWarn = warn;

  if (!window.UI || !UI.tab) return;
  UI.tab({
    id: 'meshmgr',
    group: 'More',
    order: 94,
    title: t('Mesh manager'),
    heading: t('Mesh manager'),
    icon: 'overview',
    color: 'linear-gradient(#5e5ce6, #3634a3)',
    desc: t('The computers that accepted this one as their manager'),
    hidden: (s) => !(s.mgr && s.mgr.on),
    build(body) {
      const { api } = UI;
      const list = UI.el('div');
      const result = UI.note('warn', '');
      const all = UI.button(t('Unlock all'), () => api.unlocker && api.unlocker('unlockAll', lockedIds), 'small primary');
      const unlock = unlockPeers({ noList: true, on: (v) => api.unlocker && api.unlocker('on', v), unlock: () => {} });
      body.append(
        UI.card(t('Computers'), [list, result], { actions: [all] }),
        UI.card(t('Biometric unlock'), [unlock.el]),
      );
      let lockedIds = [];
      const go = (to, what) => api.setMgr({ act: { to, do: what } });
      const strong = (d, what, label) => warn({
        title: t('{action} {computer}?', { action: label, computer: d.name }),
        lines: [t('Anything open on {computer} that isn’t saved may be lost.', { computer: d.name })],
        ok: label, danger: true,
      }, () => go(d.id, what));
      let lastKey = '';
      return (s) => {
        const mg = s.mgr || {};
        const me = { computers: (mg.computers || []).filter((d) => d.power === 'accepted').map((d) => ({ ...d, power: true, unlock: d.unlock === 'accepted' })), result: mg.result };
        const u = s.unlocker || null;
        unlock.render(me.computers.some((d) => d.unlock) ? u : null);
        result.set(me.result ? t(WHY[me.result] || me.result) : '');
        const target = (id) => ((u && u.on && u.targets) || []).find((x) => x.id === id) || null;
        lockedIds = me.computers.filter((d) => { const x = target(d.id); return d.unlock && d.pro && x && x.set && x.on && x.locked; }).map((d) => d.id);
        all.hidden = !lockedIds.length;
        all.disabled = !!(u && u.busy);
        const key = JSON.stringify([me, u && u.targets, u && u.busy, u && u.on]);
        if (key === lastKey) return;
        lastKey = key;
        const rows = [];
        for (const d of me.computers) {
          const acts = [];
          const can = d.can || {};
          if (d.power) {
            if (d.wake) acts.push(UI.button(t('Wake'), () => go(d.id, 'wake'), 'small'));
            if (can.lock) acts.push(UI.button(t('Lock'), () => go(d.id, 'lock'), 'small'));
            if (can.sleep) acts.push(UI.button(t('Sleep'), () => go(d.id, 'sleep'), 'small'));
            if (can.restart) acts.push(UI.button(t('Restart'), () => strong(d, 'restart', t('Restart')), 'small'));
            if (can.shutdown) acts.push(UI.button(t('Shut down'), () => strong(d, 'shutdown', t('Shut down')), 'small'));
          }
          const x = target(d.id);
          const what = [d.power ? t('Power') : '', d.unlock && d.pro ? t('Unlock') : ''].filter(Boolean).join(', ');
          const state = !d.online ? t('Not connected') : !d.direct ? t('Connected through another computer: connect it to this one directly') : x && x.locked ? t('Locked') : t('Connected');
          rows.push(named(UI.row(d.name, state + '. ' + t('Accepted: {features}', { features: what }), acts, literal)));
          // Unlock is always listed, with what is still missing until it can (as on its Overview).
          const raw = (mg.computers || []).find((c) => c.id === d.id) || d;
          const line = unlockLine(raw, u, x);
          const r = named(UI.row(t('Biometric unlock'), line.hint, line.btns, literal));
          r.classList.add('mgr-sub-row');
          if (!line.ready) r.classList.add('mgr-gray');
          rows.push(r);
        }
        if (!rows.length) rows.push(named(UI.row(t('No computer added yet'), t('Add computers in Multi-device › Mesh managers; each one accepts on its own screen'), [], literal)));
        list.replaceChildren(...rows);
      };
    },
  });
})();