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.

125 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith, Erdoğan Yeşil. GPL-3.0, see LICENSE.
// Main process (Linux) with Multi-device on (docs/multi-device.md): ../main.js starts this file instead
// of its own code when multi.json says so. ../main.js over the mesh (hub.js) instead of one peer, as
// windows/mesh/main.js is to windows/main.js; computers connect over the network only (no Bluetooth
// with them), phones as before; the screen goes to the selected device. When a fix in ../main.js
// applies here too, make it in both. ../main.js: Follows windows/main.js: L0–L2 discovery, pairing, clipboard, the other screen in a
// window; L3 mouse and keyboard (kvm.js + linux-helper); L4 the host role (server, pairing
// responder, peer.js with P.swapRole: Linux ↔ Linux, Linux ↔ PC); L5 this screen and sound on the
// other computer, files, notifications, wake; L6 Wayland (portal screen capture; input through the
// helper's uinput backend); L7 packages (package.json "build"); L8 the shared folder (Samba + GVFS),
// copy/paste of files with shortcuts, file drags across the edge, the file managers' Send to, and
// Extend (a virtual monitor from Mutter on Wayland, a spare output on X11).
const { lanType } = require('../../shared/lantype.js'); // Wi-Fi or Ethernet for Overview (#140)
const FolderMenu = require('../../shared/foldermenu.js'); // the file manager's Share this folder
const { app, BrowserWindow, Tray, Menu, nativeImage, nativeTheme, Notification } = require('electron');
const { Updates } = require('../../shared/updates.js');
const { aboutInfo } = require('../../shared/about.js');
const { spawn } = require('child_process');
const crypto = require('crypto');
const os = require('os');
const path = require('path');
const P = require('../../shared/protocol.js');
const { createPhoneBatteryWatch, showDesktopNotification } = require('../../shared/battery-alerts.js');
const { receivedDir } = require('../../shared/received.js'); // General › Received files
const CL = require('../../shared/cursorlock.js');
const trayMenu = require('../../shared/traymenu.js');
const I18n = require('../../shared/i18n.js');
const Look = require('../../shared/look.js');
let ownSound = null; // This device's extra speakers (shared/own-sound.js)
let pcNowRef = null; // what plays here (shared/pcnow.js), for Calls › Pause what plays here
let i18n = I18n.create('en');
const t = (...args) => i18n.t(...args);
const store = require('../store');
const { Discovery, interfaces, isIPv4, defaultIface, rankAddresses, ifaceChoices } = require('../discovery');
const { LinkManager } = require('./links');
const { Mesh } = require('../../shared/mesh.js');
const { Hub } = require('./hub');
const { Server } = require('./server');
const { installProximityLock } = require('../../shared/proximity-lock-desktop.js');
const { Pairing: HostPairing } = require('./hostpair');
const identity = require('../identity');
const Screen = require('../screen');
const Clip = require('./clip');
const Helper = require('./helper'); // Multi-device's helper (several watched sides), else the one-to-one one
const Kvm = require('./kvm');
const { AutoJoin } = require('./autojoin');
const LayoutSync = require('./layout-sync'); // the mesh's shared layout (docs/mesh.md)
const Hud = require('../hud');
const Sound = require('../sound');
const FileDrop = require('../filedrop');
const FileRecv = require('../filerecv');
const DragRecv = require('../dragrecv');
const { FilesSet } = require('../../shared/files-mesh.js');
const { FileDropSet } = require('../../shared/filedrop-mesh.js');
const FileClip = require('../fclip');
const MeshFileClip = require('../../shared/fclip-mesh.js').meshFileClip(FileClip);
const Smb = require('../smb');
const { SmbSet } = require('../../shared/smb-mesh.js');
const { MeshShadow } = require('../../shared/mesh-shadow.js');
const { SoundSet } = require('../../shared/sound-mesh.js');
const { PeerLogs } = require('../../shared/peerlogs.js');
const { startDebug } = require('../../shared/debug-start.js');
const SendTo = require('../sendto');
const Vdd = require('../vdd');
const PcScreen = require('../pcscreen');
const Sender = require('../sender');
const Notifs = require('./notifs');
const Wake = require('../wake');
const theme = require('../theme');
const Terminal = require('../terminal');
const Sshd = require('../sshd');
const Apps = require('../apps');
const PcApps = require('../pcapps');
const PeerApps = require('../peerapps');
const desktopApps = require('../desktopapps');
const loopback = require('../loopback');
loopback.usePids(() => require('electron').app.getAppMetrics().map((m) => m.pid)); // TwinDesk's own streams stay out of what Send sound captures
const autostart = require('../autostart');
const { FEATURES: PAIR_FEATURES } = require('../pairsync');
const { PhoneLink } = require('./phone-link');
const { Wired } = require('./wired');
const { PhoneDrive } = require('../phonedrive');
const { Phone } = require('./phone');
const { PhoneBridge } = require('./phone-bridge');
const { PhoneViews } = require('../phoneview');
const { PhoneSet } = require('./phones');
const { Adb } = require('../adb');
const setupIpc = require('./ipc');
const system = require('../system');
const { LiveProgress } = require('../liveprogress');
const { BleHost, BlePhones } = require('../../shared/blepipe.js'); // no BleGuest: computers over the network only
const { blePolicy, wifiQuiet } = require('../../shared/blepolicy.js');
const { NetLink } = require('../../shared/netlink.js');
const { Wifi } = require('../wifi');
const { apply: applySettings, migrateKvm, load: loadSettings, save: storeSettings } = require('./settings');

// ../main.js has set the command-line switches (WebRTC, PipeWire) and the user data folder before handing over.
if (!app.requestSingleInstanceLock()) {
  app.quit();
} else {
  Menu.setApplicationMenu(null); // its accelerators would steal keys meant for the other computer
  // Starting TwinDesk again shows the window (no tray on some desktops); a Mac app's launcher starts
  // "twindesk --mac-app=<id>": open that app instead; the file managers' Send to, --send-files.
  app.on('second-instance', (_e, argv) => {
    if (sendTo && sendTo.handle(argv)) return;
    if (shareFolderArg(argv)) return; // the file manager's Share this folder
    if (!openMacAppArg(argv)) showMain();
  });
  app.whenReady().then(start);
}

let mainWin = null;
let tray = null;
let hud = null;
let about = null; // shared/about.js, read once for the About page
let quitting = false;
let discovery = null;
let autoJoin = null; // autojoin.js: introduces devices to each other (docs/mesh.md)
let hub = null; // hub.js: every paired device (pooled features use its bus and mesh)
let iosNet = null; // shared/iosnet.js: iPhones on a USB cable
let links = null; // links.js: our guest links, one per host
let mesh = null; // shared/mesh.js: the device registry and roster
let link = null; // hub.facade: the SELECTED device, for every one-to-one feature
let devctl = null; // Overview's controls of the selected device (shared/devctl.js)
let chats = null; // Messages' chat apps from a phone, kept per phone (shared/chats.js)
let settings = null;
const batteryAlerts = createPhoneBatteryWatch({
  getEnabled: () => settings?.notifs?.batteryAlerts === true,
  notify: (alert) => showDesktopNotification(alert, { Notification, t, onClick: () => { if (!quitting) showMain(); } }),
});
let awake = null; // shared/keepawake.js
let device = null;
let drive = null; // File Sharing › TwinDesk Drive (shared/drive-host.js createMesh), only once it's on
let folders = null; // File Sharing › Shared folders and the Share folder sheet (shared/folders-host.js)
let drop = null; // Drop: one conversation with every device (shared/drop-host.js)
let web = null; // TwinDesk Web (../web.js), beside the mesh as in the one-to-one app
let screen = null;
let viewers = null; // Monitor 2 per device (shared/screen-viewers.js, #256)
let clip = null;
let wlClipboardMissing = false;
let helper = null;
let kvm = null;
let dbg = null; // Debug (shared/debug-start.js): this computer's tools and the mesh's
let localApi = null; // General › Local API (shared/localapi.js), with Debug's calls
let fileShelf = null; // File Shelf: its windows (shared/file-shelf.js FileShelves), made when first opened
let taskAlerts = null; // Local API › task alerts (shared/task-alerts.js); its server attaches when it is up
let layoutSync = null; // layout-sync.js: where every paired device sits; the kvm's edges come from it
let sound = null;
let mic = null; // Audio › Microphone (shared/mic.js), loaded only while one of its switches is on
let rezume = null; // ReZume (shared/rezume.js), only once it's turned on, and only with one phone (shared/rezume-solo.js)
let rezumeShelf = null; // … its notification and taskbar button (shared/rezume-shelf.js)
let rzSolo = null; // shared/rezume-solo.js: the device ReZume is with (picked on its page; a phone alone without a pick)
let camShare = null; // Camera tab: a camera picked at the top here, this one's to every computer picked (shared/cam-multi.js)
let vcam = null; // Camera: the running camera's picture, to the tab and the virtual camera (shared/vcam.js, ../vcam.js)
let fileDrop = null;
let fileRecv = null;
let fileClip = null;
let smb = null;
let sendTo = null;
let vdd = null;
let pcScreen = null;
let notifs = null;
let historyKeeper = null; // Clipboard and Notifications › History: kept encrypted when asked (shared/histkeeper.js)
let wake = null;
let updates = null;
let updateNote = null; // the update notification, kept so it isn't collected before a click
let pairSync = null;
let termNames = null; // Terminal nicknames, the mesh's (shared/term-names.js)
let consent = null; // each device's own two-way switches (shared/consent.js)
let edges = null; // the whole mesh's (shared/mesh-edges.js): the matrix
let meshView = null; // the mesh's computers for a phone, read only (shared/mesh-view.js)
let mgrGrants = '';
let padShare = null; // controller sharing (shared/pad-share.js)
let mgr = null; // mesh managers (shared/mesh-mgr.js): a manager in TwinDesk Professional, managed in any edition
let unlocker = null; // Biometric unlock from this computer (shared/unlock-client.js)
let terminal = null;
let sshd = null;
let apps = null;
let pcApps = null;
let peerApps = null;
let pendingMacApp = null; // {id, until}: opened once the Mac connects (2 min)
let wired = null; // wired.js, with the phone
let hostServer = null; // server.js, once the certificate exists
let proximityLock = null;
let phoneRemote = null; // each phone's Remote page: touchpad, keyboard and gamepad here (shared/perphone.js phoneRemote)
let deck = null; // the Deck (shared/deck.js): each phone's (and web device's) buttons run here
let iosSign = null; // shared/iossign.js: TwinDesk iPhone, one iPhone at a time, as in the one-to-one app (shared/perphone.js anyPhone)
let modulesAtStart = []; // General › Modules: the ones off at start aren't loaded (fixed for this run)
let nowPlaying = null; // what plays on each phone, for the Overview's media controls (shared/perphone.js)
let btAudio = null; // the phone's sound here over Bluetooth (shared/btaudio.js), for the first phone
let phone = null; // A phone as the peer: phone.js (its .bridge: phone-bridge.js)
let phonePhoto = null; // Camera › Take a photo / Scan document (shared/phonephoto.js), made in startPhone
let ios = null; // shared/ios-mesh.js: an iPhone through a USB cable (ours or another computer's)
let android = null; // shared/android-relay.js: an Android phone's screen through the computer it's connected to
let phoneDrive = null; // its storage as a drive here (phonedrive.js), the first phone's
// (the screen and apps of a phone in windows here: phoneview.js, per phone, phone.views for the active one)
let bleHost = null; // Bluetooth, for devices not on this network: we host (blepipe.js, the helper's ble.c)
let bleGuest = null; // never set: with Multi-device, computers connect over the network only
let blePhones = null; // phones that advertise: we connect to them
let bleOff = false; // General's Turn off Bluetooth on Wi-Fi connections, in effect (bleQuiet)
const bleQuiet = wifiQuiet();
let net = null; // Wi-Fi for a session through Bluetooth (netlink.js)
let wifi = null; // this computer's Wi-Fi for it: hosting, joining (wifi.js, NetworkManager)
let pendingView = null; // a phone window waiting for wireless debugging (phoneViews.onNoAdb)
let lastMode = 'home';
let fw = { checking: true, ok: null, message: 'Checking…' };
const session = system.session();
// Started at login (tray only), or by a Mac app's launcher (that app only).
const startHidden = process.argv.includes('--hidden') || process.argv.some((a) => a.startsWith('--mac-app='));
let lastPairPhase = null;

function loadDevice() {
  let d = store.read('device.json', null);
  if (!d || typeof d.id !== 'string') {
    d = { id: crypto.randomUUID() };
    store.write('device.json', d);
  }
  return { id: d.id, name: os.hostname() };
}

function start() {
  theme.start();
  autostart.refresh(); // an older entry gets the output redirect (#162)
  device = loadDevice();
  settings = loadSettings(store); // settings.json and the mesh's own in multi.json (settings.js)
  modulesAtStart = require('../../shared/modules.js').normalize(settings.modules).off.filter((id) => id !== 'multi'); // the window's scripts are fixed at load
  require('../../shared/edition.js').moduleOff(modulesAtStart.includes('fullkvm')); // General › Modules › Full KVM, before the helper is made
  require('../../shared/inputlane.js').setLaneProtocol(settings.app.inputProtocol); // General › Advanced, before any lane binds
  // Quiet links (#143): an idle session stops pinging every second; General › Advanced › Keep pinging.
  require('../../shared/quiet.js').use(() => !!(settings && settings.app && settings.app.keepPinging === true));
  require('../../shared/tailnet.js').use(() => !(settings && settings.net && settings.net.tailscale === false)); // General › Tailscale (#161)
  theme.setPref(settings.ui.theme);
  i18n = I18n.create(I18n.resolveLanguage(settings.ui.language, app.getLocale()));

  discovery = new Discovery(device);
  discovery.on('change', pushState);
  // Asleep: every session we host ends and dark wakes refuse them; awake, each device is invited back.
  require('./sleepwake.js').sleepWake({ powerMonitor: require('electron').powerMonitor, server: () => hostServer, discovery: () => discovery });
  discovery.on('invite', () => { pushState(); showMain(); }); // another computer wants to connect: Pair is focused
  discovery.start();

  // The mesh (docs/mesh.md): one guest link per paired host (links.js), the device registry (mesh),
  // and the hub that joins them to the host side (startHost attaches it) and to the features:
  // pooled ones (clipboard, notifications) use hub.bus, the one-to-one ones use `link`, the facade of
  // the selected device.
  links = new LinkManager({ device, resolveAddress: (macId) => discovery.get(macId) });
  mesh = new Mesh({ selfId: device.id });
  hub = new Hub({ device, links, mesh });
  // ReZume with one device of the mesh, picked on the ReZume page and the same on both (settings.rezume.with).
  rzSolo = require('../../shared/rezume-solo.js').soloLink({ bus: hub.bus, sessions: hub.sessions, partner: {
    get: () => settings.rezume.with,
    set: (v) => { settings.rezume.with = v; saveSettings(); pushState(); },
  } });
  // ReZume off here (not loaded): still answer the phone's policy, so it shows ReZume as off
  hub.bus.on(P.T.RZ_POLICY, (m, from) => { if (!rezume && from && from === rzSolo.id()) hub.bus.send(from, { t: P.T.RZ_POLICY, on: false, web: false, docs: false, apps: false, push: false }); });
  link = hub.facade;
  // General › Keep the display awake while a computer is connected, or Always (shared/keepawake.js, #240).
  awake = require('../../shared/keepawake.js').keepAwake(() => settings.app.keepAwake !== false && (settings.app.keepAwakeAlways === true || (hub && hub._connectedIds().length > 0)));
  // Overview's controls of the selected device (a computer or a phone), and this computer's for it.
  const { DevCtl } = require('../../shared/devctl.js');
  const { DevLocal } = require('../../shared/devlocal.js');
  // A DevCtl per device (shared/devctl-mesh.js): each device's Overview can reach this computer, whichever
  // device is selected here; Overview shows the selected device's.
  const watching = () => !!(mainWin && !mainWin.isDestroyed() && mainWin.isVisible() && !mainWin.isMinimized()); // Overview may show the other side's controls (shared/devctl.js Looking)
  const devLocal = new DevLocal();
  devctl = require('../../shared/devctl-mesh.js').onHub(hub, {
    local: devLocal,
    make: (dl, pid) => new DevCtl({
      link: dl, local: devLocal, sharedLocal: true, version: app.getVersion(),
      watching: () => watching() && hub.selectedId === pid, // asks only for the device Overview shows
      adb: () => { // the phone's wireless debugging, for that phone only
        if (hub.selectedId !== pid) return null;
        const br = phone && phone.bridge;
        return br && br.state === 'ready' && br.serial ? { adb: br.adb, serial: br.serial } : null;
      },
    }),
  });
  devctl.on('change', pushState);
  app.on('browser-window-focus', () => devctl && devctl.look()); // back on screen: a fresh state of the other side now
  hub.on('selected', () => devctl.look()); // Overview shows another device: its fresh state
  // The selected device runs an older TwinDesk (shared/appinfo.js): say so once.
  devctl.on('outdated', (o) => {
    const { FEATURES } = require('../../shared/appinfo.js');
    const title = o.version ? t('{name} has an older TwinDesk ({version})', { name: o.name || t('The other device'), version: o.version })
      : t('{name} has an older TwinDesk', { name: o.name || t('The other device') });
    const body = o.missing.length ? t('Update it there for: {features}', { features: o.missing.map((k) => t(FEATURES[k])).join(', ') })
      : t('Update it there: some features need the same version on both');
    try { new Notification({ title, body }).show(); } catch {}
  });
  const { Chats } = require('../../shared/chats.js');
  chats = new Chats({ // every phone's conversations, each under its own id; the Messages page's phone answered (#313)
    mesh: { bus: hub.bus, isPhone: (id) => { const s = hub.sessions.get(id); return !!s && P.isPhoneOs(s.peerOs); } },
    who: () => (phoneLink && phoneLink.current && phoneLink.current.deviceId) || '',
    dir: app.getPath('userData'), want: () => settings.ui.chats === true, onChange: pushState });
  hub.on('change', () => {
    discovery.wantProbes = link.snapshot().link.state !== 'connected'; // probe every 10 s only while not connected
    pushState();
  });
  startHost();
  autoJoin = new AutoJoin({ hub, enabled: () => settings.mesh.autoJoin !== false, addrs: () => ownAddresses() });
  // Each device's own two-way switches (shared/consent.js): the settings are the selected device's pair,
  // every other device's is its saved one. The clipboard, notifications and files serve them all at once.
  consent = require('../../shared/consent.js').consent({
    features: PAIR_FEATURES, settings: () => settings, selectedId: () => hub.selectedId,
    send: (to, m) => hub.bus.send(to, m), save: saveSettings,
  });
  hub.consent = consent; // sound and the pointer read each device's own pair from the hub (shared/sound-mesh.js, kvm.js)
  clip = new Clip({ bus: hub.bus, mesh, consent, getSettings: () => settings.clipboard, onChange: pushState, clipboard: require('../wlclip').clipboard(), session: (id) => hub.sessions.get(id), popup: (kind, text) => hud && hud.show(kind, text) }); // wl-clipboard where Wayland needs it (#97)
  wlClipboardMissing = require('../wlclip').missing(); // other apps' copies unseen here (#97)
  if (wlClipboardMissing) console.log('[clip] Wayland without wl-clipboard (wl-paste, wl-copy): copies made in other apps aren’t seen here, so they aren’t sent');
  // Monitor 2: the selected device's screen, but while its window is open it stays with the device it shows
  // (#256: the pointer's next crossing moved the selection, and the picture with it). hub.sticky.
  const screenLink = hub.sticky(() => !!(screen && screen.win && !screen.win.isDestroyed() && screen.win.isVisible()), { remember: ['screen.state'] }); // whether that device shares its screen
  const { channel: screenCh } = require('../../shared/screen-ch.js');
  screen = new Screen({
    link: screenCh(screenLink, 0), // stream 0 (shared/screen-ch.js): another stream's messages aren't for it
    multi: true, // it says so in screen.policy: a sharer may send more of its screens, each in a window of its own
    clip,
    inputAllowed: () => !kvm || kvm.mode === 'home', // no Monitor 2 input while driving or driven
    settings,
    saveSettings,
    onChange: () => { screenLink.follow(); pushState(); }, // closed: it follows the selection again
    isQuitting: () => quitting, selfId: device.id,
  });
  // Monitor 2 per device (#256, shared/screen-viewers.js): Open for a device the first one isn't showing,
  // while it shows another, opens one of that device's own; files dropped on it go to that device.
  viewers = require('../../shared/screen-viewers.js').screenViewers({
    hub, primary: () => screen, primaryLink: screenLink,
    make: (l, pid) => {
      const v = new Screen({ link: screenCh(l, 0), multi: true, clip, inputAllowed: () => !kvm || kvm.mode === 'home', settings, saveSettings, onChange: pushState, isQuitting: () => quitting, selfId: device.id });
      v.fileDrop = { drop: (...a) => { const u = fileDrop.unit(pid); if (u) u.drop(...a); } };
      return v;
    },
  });
  // More screens of one computer (screen.state with ch, shared/screen-ch.js): a window per stream, made
  // when the first one starts and kept for the next time (at most 3 per computer). Nothing until then.
  const extraViewers = new Map(); // `${device}#${ch}` -> Screen
  hub.bus.on(P.T.SCREEN_STATE, (m, from) => {
    const ch = m && Number.isInteger(m.ch) && m.ch > 0 && m.ch <= 3 ? m.ch : 0;
    if (!ch) return;
    const k = from + '#' + ch;
    let v = extraViewers.get(k);
    if (!v) {
      if (m.on !== true) return;
      v = new Screen({ link: screenCh(hub.scoped(from), ch), clip, inputAllowed: () => !kvm || kvm.mode === 'home', settings, saveSettings, onChange: pushState, isQuitting: () => quitting, selfId: device.id });
      v.fileDrop = { drop: (...a) => { const u = fileDrop.unit(from); if (u) u.drop(...a); } };
      extraViewers.set(k, v);
      v._onState(m); // it was made after this message went to the others
      v.open(false);
    } else if (m.on === true && !(v.win && !v.win.isDestroyed() && v.win.isVisible())) v.open(false);
    else if (m.on !== true && v.win && !v.win.isDestroyed()) v.win.hide(); // that stream stopped: its window goes
  });
  // Sending: a FileDrop per device (shared/filedrop-mesh.js), so a crossing mid-send doesn't stop it.
  fileDrop = new FileDropSet({
    hub, FileDrop, settings, outboxFile: path.join(app.getPath('userData'), 'outbox.json'),
    make: (scoped, id, outbox) => new FileDrop({ link: scoped, settings, outbox, sends: () => consent.get(id, 'files', 'out'), onProgress: () => { screen.sendDropProgress(fillAll(fileDrop.view())); pushState(); } }),
  });
  screen.fileDrop = fileDrop;
  // Monitor 2 open and showing nothing follows a device that starts sharing (#256: a PC driving this one
  // shared its Extend screen while another device was selected, and nothing came).
  hub.bus.on(P.T.SCREEN_STATE, (m, from) => {
    if (m.on !== true || from === screenLink.id || screen.state.state === 'on') return;
    if (m.by && m.by !== device.id) return; // another computer asked it to share: it's watching it, not us
    if (viewers && viewers.showing(from)) return; // a Monitor 2 of its own shows it already
    const w = screen.win;
    if (!w || w.isDestroyed() || !w.isVisible()) return;
    console.log(`[screen] Monitor 2 follows ${from}: it shares its screen`);
    hub.select(from);
    screenLink.moveTo(from); // open, it doesn't follow the selection by itself
  });
  sound = new SoundSet({ Sound, hub, settings, save: saveSettings, onChange: pushState }); // a Sound per device, both ways at once (shared/sound-mesh.js)
  // This computer's sound on more of its own speakers (Audio › This device › Choose devices), from loopback.js's
  // source, which TwinDesk's own streams never reach: nothing played here is heard again.
  ownSound = new (require('../../shared/own-sound.js').OwnSound)({ settings: () => settings, save: saveSettings, onChange: pushState, capture: { source: require('../loopback').LABEL, acquire: () => require('../loopback').acquire().then(() => true, () => false), release: () => require('../loopback').release() }, dir: require('path').join(__dirname, '..'), unsupported: 'PulseAudio or PipeWire couldn’t give TwinDesk this computer’s sound without its own, so nothing plays on more speakers' });
  ownSound.apply();
  loadMic();
  smb = new SmbSet({ Smb, hub, settings, save: saveSettings, onChange: pushState }); // a folder per device, ours to all (shared/smb-mesh.js)
  // Terminal, this computer to another: one per computer (shared/papps-mesh.js), each with its own alias,
  // `ssh twindesk-<name>`, and its own pair's switch; `ssh twindesk` is the selected device's (#313).
  const SshConfig = require('../../shared/sshconfig.js');
  // Nicknames (shared/term-names.js): what each computer goes by in `ssh twindesk-<name>`, the mesh's list.
  termNames = require('../../shared/term-names.js').termNames({
    bus: hub.bus, mesh, selfId: device.id, settings: () => settings, save: saveSettings,
    isPhone: (id) => { const x = hub.sessions.get(id); return !!x && P.isPhoneOs(x.peerOs); },
    names: () => Object.fromEntries([[device.id, device.name], ...hub.peers({ indirect: true }).filter((d) => !P.isPhoneOs(d.os)).map((d) => [d.id, d.name || ''])]),
    onChange: (ids) => {
      for (const id of ids) {
        const u = terminal && terminal.byId.get(id);
        const x = hub.sessions.get(id);
        if (u && x) u.rename(termNames.alias(id, x.displayName()));
      }
      pushState();
    },
  });
  terminal = require('../../shared/papps-mesh.js').appsSet({
    selectedId: () => hub.selectedId, empty: { status: 'no_mac', message: '', user: null, command: 'ssh ' + SshConfig.ALIAS },
    all: ['apply'], selected: ['open'],
  });
  require('../../shared/scoped-link.js').eachDevice(hub, (pid, l) => {
    const x = hub.sessions.get(pid);
    if (!x || P.isPhoneOs(x.peerOs)) return;
    terminal.ensure(pid, () => new Terminal({
      link: l, settings, onChange: pushState, alias: termNames.alias(pid, x.displayName()),
      enabled: () => consent.get(pid, 'terminal', 'in'), isDefault: () => hub.selectedId === pid,
      address: () => (l.current && l.current.address) || '', peerName: () => (l.current && l.current.name) || '',
    }));
  });
  hub.on('selected', (pid) => { // `ssh twindesk`: the selected device's, or none
    const u = terminal.byId.get(pid);
    if (u) u.takeDefault();
    else try { SshConfig.setHost(null); } catch (_) { /* config not writable */ }
  });
  sshd = new Sshd({ link, bus: hub.bus, consent, settings, save: saveSettings, onChange: pushState }); // every device's key, by its own pair
  // The helper: X11 (XInput2 + XTest), or on Wayland its uinput backend when /dev/uinput is ours.
  helper = new Helper(() => system.inputBlocker(session));
  if (require('../../shared/edition.js').fullKvm()) require('../fullkvm/manager.js').attach({ helper, hub, name: () => device.name, settings: () => settings, save: saveSettings, may: (id, cls) => (cls === 'phone' ? true : !!mgr && mgr.mayUnlock(id)) }); // phones: only directly connected; computers: mesh managers it accepted for Unlock (shared/mesh-mgr.js) // the Full KVM build: its tab and service (docs/full-kvm.md)
  hud = new Hud(() => settings);
  // Files from every device, each on its own link: the computer driving this one isn't selected here
  // (shared/files-mesh.js). fileRecv and dragRecv are the set's single-receiver API.
  // A phone's Send to another computer of the mesh: taken here and passed on (shared/files-relay.js).
  const filesRelay = require('../../shared/files-relay.js').filesRelay({
    selfId: device.id,
    isPhone: (pid) => { const x = hub.sessions.get(pid); return !!x && P.isPhoneOs(x.peerOs); },
    connected: (pid) => { const x = hub.sessions.get(pid); return !!x && x.connected; },
    sendTo: (pid, paths) => { const u = fileDrop && fileDrop.unit(pid); if (!u) return false; u.send(paths); return true; },
    nameOf: (pid) => { const x = hub.sessions.get(pid); return x ? x.displayName() : pid; },
    notify: (key, vars) => hud.show('driven', { key: key.replace('file(s)', vars.count === 1 ? 'file' : 'files'), vars }),
  });
  const files = new FilesSet({
    hub, partner: () => (kvm && kvm.mode === 'driven' ? kvm.partner : null),
    make: (scoped) => ({
      fileRecv: new FileRecv({ link: scoped, helper, settings, accepts: () => consent.get(scoped.id, 'files', 'in'), onChange: pushState, relayDir: (to, batch) => filesRelay.dir(scoped.id, to, batch) }),
      dragRecv: new DragRecv({ link: scoped, helper, settings, accepts: () => consent.get(scoped.id, 'files', 'in'), isDriven: () => kvm && kvm.mode === 'driven', popup: (kind, text) => hud.show(kind, text), onChange: pushState }),
    }),
  });
  fileRecv = files.fileRecv;
  const dragRecv = files.dragRecv;
  // Settings from before the cursor edges: one paired device takes the side its old pcSide gave it.
  if (migrateKvm(settings, hub.peers().map((p) => p.id))) saveSettings();
  // The shared layout: one map of the paired devices for the whole mesh (its own pool, docs/mesh.md).
  layoutSync = new LayoutSync({
    bus: hub.bus,
    mesh,
    selfId: device.id,
    storage: { get: () => settings.layout, set: (l) => { settings.layout = l; saveSettings(); } },
    knownIds: () => hub.peers({ indirect: true }).map((p) => p.id), // with those known through a peer: one map everywhere
    canDrive: (pid) => { const s = hub.sessions.get(pid); return !!s && s.connected; }, // the Multi-device tab's reach
    // A phone known through another device (a peer's, or an iPhone on a Mac's cable) is one too.
    endsChain: (pid) => { const s = hub.sessions.get(pid); if (s) return P.isPhoneOs(s.peerOs); const k = hub.mesh.known().find((x) => x.id === pid); return !!k && P.isPhoneOs(k.os); },
    // The monitor map (#225): ours from Electron, the others' kept for when they are offline.
    online: (pid) => { const p = hub.peers({ indirect: true }).find((x) => x.id === pid); return !!p && (p.state === 'connected' || p.state === 'via'); },
    myDisplays: () => require('../../shared/screen-mesh.js').fromElectron(require('electron').screen),
    // The phones connected here, at their real size and way round (#375; their phone.info display)
    phoneDisplays: () => {
      const out = {};
      for (const [id, u] of (phone && phone.byId) || []) if (u.link && u.link.current) out[id] = require('../../shared/screen-mesh.js').phoneDisplays(u.phone && u.phone.info);
      return out;
    },
    displaysStorage: { get: () => settings.layoutDisplays || null, set: (m) => { settings.layoutDisplays = m; saveSettings(); } },
    legacyEdges: () => settings.kvm.edges, // settings from before the layout: once
    onChange: () => { if (kvm) kvm.layoutChanged(); pushState(); },
  });
  for (const ev of ['display-added', 'display-removed', 'display-metrics-changed']) require('electron').screen.on(ev, () => layoutSync.displaysChanged());
  kvm = new Kvm({ hub, layoutSync, helper, clip, fileDrop, fileRecv, dragRecv, settings, save: saveSettings, onChange: onKvmChange });
  const shadow = new MeshShadow({ hub, kvm: () => kvm, sound: () => sound, mic: () => mic, settings: () => settings }).start(); // the graph beside today's routing, logs only (docs/mesh-graph.md, step 1)
  dbg = startDebug({ // Debug: any device of the mesh, from here or the code agent's MCP server (docs/debug.md)
    // The Android phones connected here: Debug answers for them (shared/phone-debug.js).
    phones: () => (phone ? phone.all : []).filter((u) => u.link.current && u.link.current.os === P.OS.ANDROID).map((u) => ({
      id: u.link.current.deviceId, name: u.link.current.name, info: u.phone.info || {},
      adb: () => (u.bridge.serial && u.bridge.state === 'ready' ? { bin: u.bridge.adb.bin, serial: u.bridge.serial } : null),
      bridge: { state: u.bridge.state, message: u.bridge.message },
    })),
    app, hub, device, settings, save: saveSettings, kvm: () => kvm, shadow, helper, onChange: () => pushState(),
    updates: () => updates, // its SelfUpdate: an update sent through the mesh installs as the app's own would
    fullkvm: require('../../shared/edition.js').fullKvm() ? require('../fullkvm/manager.js') : null,
  });
  { // General › Local API (shared/localapi.js): in Multi-device, Debug's too, for the code agent's MCP server (docs/debug.md)
    const { LocalApi } = require('../../shared/localapi.js');
    if (!taskAlerts) taskAlerts = new (require('../../shared/task-alerts.js').TaskAlerts)();
    localApi = new LocalApi({ dir: app.getPath('userData'), actions: {
      status: () => { const s = hub.selectedId && hub.sessions.get(hub.selectedId); return { connected: !!(s && s.connected), device: s && s.connected ? s.displayName() : '' }; },
      send: () => null, // Send files of the selected device is the window's; not here yet
      clipboard: (text) => require('electron').clipboard.writeText(text), // then Clipboard shares it by its rules
      debug: dbg.api,
      taskAlerts, // terminal task alerts to the phones (shared/task-alerts.js, bin/twindesk-notify)
    } });
    if (settings.app.localApi) applyLocalApi();
  }
  new PeerLogs({ bus: hub.bus, nameOf: (id) => { const s = hub.sessions.get(id); return s ? s.displayName() : id; }, dir: () => require('../../shared/applog.js').dir(), share: () => settings.mesh.shareLogs !== false, collect: () => settings.mesh.collectLogs !== false }).start(); // the other devices' logs, copied here (docs/peer-logs.md)
  require('../../shared/applog.js').linkStats(() => kvm.linkSample()); // the link's line in the log every 30 s
  // Popups: a {key, vars} is translated in the popup (hud-renderer.js) with the device names added;
  // English text with {me}/{name} (from modules not translated yet) gets the names filled in here.
  const hudShow = hud.show.bind(hud);
  const named = (v) => (v && typeof v === 'object' ? { ...v, vars: { me: (device && device.name) || t('This computer'), name: peerName(), Name: peerName(), ...(v.vars || {}) } } : fillNames(v || ''));
  hud.show = (kind, text, sub) => hudShow(kind, named(text), named(sub || '')); // device names in popups
  // Cursor sharing switched on/off (hotkey double-tap, tray, the Cursor tab or the other side): the big card.
  // ble: Over Bluetooth was switched (kvm.setShared through Bluetooth).
  kvm.onLinked = (on, here, ble) => {
    const name = link.snapshot().link.state === 'connected' ? peerName() : '';
    const key = t(P.hotkeyName(settings.keys.hotkey, 'win').replace('Windows key', 'Super'));
    const sub = !here && name ? { key: on ? 'Turned on on {name}' : 'Turned off on {name}', vars: { name } }
      : on ? { key: name ? 'With {name}. Double-tap {key} to turn it off' : 'Double-tap {key} to turn it off', vars: { name, key } }
        : { key: ble ? 'It comes back on Wi-Fi. Double-tap {key} to turn it on' : 'Double-tap {key} to turn it on', vars: { key } };
    hud.show(on ? 'linkOn' : 'linkOff', { key: on ? 'Cursor sharing on' : ble ? 'Cursor sharing off over Bluetooth' : 'Cursor sharing off' }, sub);
  };
  kvm.onWhere = (mode) => { // the switching popup
    // The device the pointer is with (the input peer, docs/mesh-graph.md), not the selected one.
    const p = kvm.partner ? hub.sessions.get(kvm.partner) : null;
    const name = p ? p.displayName() : peerName();
    if (mode === 'driving') hud.show('away', { key: kvm.keyboardOnly ? 'Typing on {name}' : 'Using {name}', vars: { name } });
    else if (mode === 'driven') hud.show('driven', { key: '{name} is using {me}', vars: { name, me: device.name } });
    else hud.show('home', { key: 'Back on {me}', vars: { me: device.name } });
  };
  // Cursor lock: the popup goes where the pointer is (the device we drive shows its own).
  kvm.onLock = (on, mode) => {
    if (mode === 'driving' && !(kvm.local && kvm.local.drives(kvm.partner))) return;
    const where = mode === 'driving' ? peerName() : device.name;
    hud.show('lock', { key: on ? 'Cursor locked on {name}' : 'Cursor unlocked', vars: { name: where } });
  };
  // Send files and drops show progress in the popup, like the PC.
  const pct = (n, total) => Math.min(99, Math.floor((n / total) * 100));
  let lastPopup = 0;
  const progressPopup = (kind, text, done) => {
    const now = Date.now();
    if (!done && now - lastPopup < 250) return;
    lastPopup = now;
    hud.show(kind, text);
  };
  // …and in a notification with a live progress bar (liveprogress.js), one each way.
  const live = new LiveProgress(path.join(__dirname, '..', 'assets', 'icon.png'));
  // The device a batch came from (shared/files-mesh.js: b.from), not the selected one.
  const fromName = (b) => { const x = b && b.from ? hub.sessions.get(b.from) : null; return x ? x.displayName() : peerName(); };
  const liveFor = { recv: null, send: null }; // the device each progress notification is about
  fileRecv.onBatchProgress = (b) => {
    liveFor.recv = b.from || null;
    if (Date.now() - b.at < 400) return; // small batches: only the "Pasted" / "Received" popup
    const part = b.total ? pct(b.got, b.total) : pct(b.done, b.count);
    const key = b.kind === 'paste'
      ? b.count === 1 ? 'Pasting {count} file from {name}' : 'Pasting {count} files from {name}'
      : b.count === 1 ? 'Receiving {count} file from {name}' : 'Receiving {count} files from {name}';
    const vars = { count: b.count, name: fromName(b), percent: part };
    progressPopup('driven', { key: key + ' · {percent} %', vars });
    live.progress('recv', t(key, vars), t('From {name}', { name: fromName(b) }), part);
  };
  // Sending: Send files, drags and pastes other devices asked for, each named by the device it goes to.
  const sendProgress = (b, name = peerName()) => {
    if (!(b.bytes > 5 * 1024 * 1024)) return;
    const file = b.itemCount > 1 ? { key: '{count} items', vars: { count: b.itemCount } } : b.name;
    const label = b.itemCount > 1 ? t('{count} items', { count: b.itemCount }) : b.name;
    if (b.done) {
      live.done('send', b.ok ? t('Sent {file}', { file: label }) : t('Not everything arrived'), t('On {name}', { name }));
      return progressPopup('away', { key: b.ok ? 'Sent {file} to {name}' : 'Not everything arrived on {name}', vars: { file, name } }, true);
    }
    progressPopup('away', { key: 'Sending {file} to {name} · {percent} %', vars: { file, name, percent: pct(b.sent, b.bytes) } });
    live.progress('send', t('Sending {file}', { file: label }), t('To {name}', { name }), pct(b.sent, b.bytes));
  };
  fileDrop.onBatchProgress = (b) => { liveFor.send = b.to || null; const x = b.to ? hub.sessions.get(b.to) : null; sendProgress(b, x ? x.displayName() : peerName()); }; // b.to: the device it goes to
  // A device that really left (not the selection moving on: its files go on, shared/filedrop-mesh.js).
  hub.bus.onPeer('closed', (id) => {
    const x = hub.sessions.get(id);
    const name = x ? x.displayName() : peerName();
    for (const tag of ['recv', 'send']) if (!liveFor[tag] || liveFor[tag] === id) live.done(tag, t('Files stopped'), t('{name} disconnected', { name }));
  });
  fileRecv.onBatch = (b) => {
    if (filesRelay.done(b)) return; // a phone's batch for another device: passed on
    live.done('recv', b.files ? t(b.files === 1 ? 'Received {count} file' : 'Received {count} files', { count: b.files }) : t('Nothing arrived'), t('From {name}', { name: fromName(b) }));
    if (b.kind === 'send' && phonePhoto && phonePhoto.arrived(b.placed)) return; // photo: copied; scan: the PDF stays in received files
    if (rezume && rezume.received(b)) return; // a document taken here with ReZume: it opens
    if (b.kind === 'paste') fileClip.pasted(b);
    else if (b.files) hud.show('driven', { key: b.files === 1 ? 'Received {count} file from {name}' : 'Received {count} files from {name}', vars: { count: b.files, name: fromName(b) } });
  };
  // Copy and paste files with the shortcuts (the helper watches the keys), with every device
  // (shared/fclip-mesh.js): a paste another device asks for goes to it through a sender of its own.
  fileClip = new MeshFileClip({
    hub, files, helper, fileDrop, settings, peerName, popup: (kind, text) => hud.show(kind, text), onChange: pushState,
    makeSender: (id) => fileDrop.unit(id),
  });
  kvm.fileClip = fileClip; // our copy/paste shortcut while driving → fclip.key
  fileClip.kvm = kvm; // …also when the keyboard isn't shared
  sendTo = new SendTo({ link, bus: hub.bus, nameOf: (pid) => { const x = hub.sessions.get(pid); return x ? x.displayName() : ''; }, fileDrop, peerName: () => (peerView() || {}).name || '', popup: (kind, text, sub) => hud.show(kind, text, sub) });
  notifs = new Notifs({
    consent,
    bus: hub.bus, mesh, settings, save: saveSettings,
    peerName: (id) => ((mesh.get(id) || {}).name || ''), selfName: () => device.name, onChange: pushState,
  });
  consent.on('change', () => { // a device's pair: its policies (and its keys) again
    clip.applySettings(); notifs.applySettings(); sshd.apply(); terminal.apply();
    if (peerApps) peerApps.apply();
    if (pcApps) pcApps.apply();
    pushState();
  });
  wake = new Wake({ link, bus: hub.bus, peer: (pid) => { const x = hub.sessions.get(pid); return x ? { name: x.displayName(), os: x.peerOs } : null; }, settings, save: saveSettings, onChange: pushState, address: () => ownAddresses()[0] });
  vdd = new Vdd({ onChange: pushState });
  // Share screen to several devices at once (shared/pcscreen-set.js), as on Windows: a PcScreen per device,
  // each on its own link and sender. The facade's one stopped sharing to a device on every crossing (#313).
  let senders = 0;
  const MeshSender = require('./sender');
  pcScreen = new (require('../../shared/pcscreen-set.js').PcScreenSet)({
    hub, model: PcScreen.displayModel, onChange: pushState,
    make: (scoped, extendFree) => {
      const pc = new PcScreen({ link: scoped, helper, sender: new MeshSender(scoped, 1000000 * ++senders), vdd, settings, popup: (kind, text) => hud.show(kind, text), inputAllowed: () => kvm.mode === 'home', onChange: pushState, needDriver: () => goTab('pc-mac') });
      pc.extendFree = extendFree;
      return pc;
    },
  });
  vdd.check(); // Extend: can this desktop add a virtual monitor? (and one left on by a crash goes)
  // On Monitor 2's link (the device it shows), not the facade: its windows are drawn there, so an app list
  // or windows from the selected device while Monitor 2 showed another were the wrong device's.
  apps = new Apps({ link: screenLink, allowed: () => consent.get(screenLink.id, 'apps', 'in'), getLanguage: () => i18n.locale, getMonitor: () => screen.win, popup: (kind, text) => hud.show(kind, text), peerName: () => { const x = screenLink.id && hub.sessions.get(screenLink.id); return x ? x.displayName() : peerName(); }, onChange: pushState, onWatch: () => screen.policy() });
  screen.apps = apps;
  // Apps from this computer and Move windows: a PcApps per device, each on its own link and sender
  // (shared/papps-mesh.js pcAppsSet), so windows go to several devices at once and each lists and opens this
  // computer's apps itself (#313).
  let appSenders = 0;
  pcApps = require('../../shared/papps-mesh.js').pcAppsSet({
    hub,
    empty: () => ({ allow: false, macAccepts: false, open: 0, streaming: 0, moved: 0, moveWindows: settings.pcApps.moveWindows, moveKey: settings.pcApps.moveKey, message: '' }),
    make: (l, pid) => new PcApps({
      link: l, allows: () => consent.get(pid, 'apps', 'out'), helper, settings, inputAllowed: () => kvm.mode === 'home', onChange: pushState,
      sender: new (require('./sender'))(l, 500000000 + 1000000 * ++appSenders), // its windows' rtc2 sessions, numbered apart from the screens'
    }),
  });
  // Another computer's apps here: a PeerApps per device, each on its own link (shared/papps-mesh.js), so
  // windows from several computers stay open and a crossing closes none of them (#313).
  peerApps = require('../../shared/papps-mesh.js').appsSet({
    selectedId: () => hub.selectedId,
    empty: { list: [], loading: false, message: '', open: 0, peerPc: true },
    merge: (v, all) => ({ ...v, open: all.reduce((n, x) => n + (x.open || 0), 0) }), // the Apps tab: the selected device's list, every window
    all: ['apply', 'acceptReZume', 'shutdown'], selected: ['refresh', 'launch'], any: ['returnWindow'],
  });
  require('../../shared/scoped-link.js').eachDevice(hub, (pid, l) => peerApps.ensure(pid, () => new PeerApps({
    link: l, settings, popup: (kind, text) => hud.show(kind, text), onChange: pushState,
    peerName: () => { const x = hub.sessions.get(pid); return x ? x.displayName() : peerName(); },
    allowed: () => consent.get(pid, 'apps', 'in'), // its own pair's "Open its apps here"
  })));
  // Apps › Move windows: a window grabbed with the move key crossed with the pointer. A
  // copy of the other computer's window goes home there (peerapps.js); one of this PC's goes over (pcapps.js).
  // In Multi-device it goes to the device the pointer went to, selected first, with what that
  // device said about taking windows (shared/mesh-movewin.js: #250, #251).
  const meshMoves = require('../../shared/mesh-movewin.js').meshMoves(hub, P.T);
  kvm.onMoveWindow = (m, to) => {
    const wid = Number(m.moving);
    if (!wid || peerApps.returnWindow(wid)) return;
    if (!settings.pcApps.moveWindows) return;
    const unit = pcApps.unit(to); // the device the pointer went to: its own PcApps (windows may be on others too)
    if (!unit) return;
    if (!meshMoves.ready(to, (v) => { unit.macAccepts = v; })) return;
    unit.moveOut(wid, m.fromX !== undefined ? { x: Number(m.fromX), y: Number(m.fromY) } : undefined).then((ok) => ok || console.log(`[apps] window not moved: ${unit.macAccepts ? 'it can’t go (Bluetooth, gone, already there)' : 'Move windows is off on the other computer'}`));
  };
  helper.on('exit', pushState);
  // General › Lock together (#322, shared/locksync.js): this computer locked, every connected computer locks too.
  const isPc = (id) => { const s = hub.sessions.get(id); return !!s && s.connected && !P.isPhoneOs(s.peerOs); };
  const lockSync = new (require('../../shared/locksync.js').LockSync)({
    platform: 'linux', helper, enabled: () => settings.app.lockTogether === true,
    send: (m) => { for (const id of hub.bus.connectedIds()) if (isPc(id)) hub.bus.send(id, m); },
  }).start();
  hub.bus.on('lock.now', (m, from) => isPc(from) && lockSync.onMessage(hub.sessions.get(from).displayName()));
  helper.on('ready', () => { sendScreens(); pushState(); });
  const { screen: displays } = require('electron');
  for (const ev of ['display-added', 'display-removed', 'display-metrics-changed']) displays.on(ev, sendScreens);
  setupNet();
  helper.start();
  // New releases on GitHub: a notification once per version, the tray item and About › Updates.
  updates = new Updates({
    current: app.getVersion(), platform: 'linux', prefer: process.env.APPIMAGE || !app.isPackaged ? 'appimage' : 'deb', getSettings: () => settings, getLanguage: () => i18n.locale, save: saveSettings, onChange: pushState,
    isBusy: () => !!(hub && hub.bus && hub.bus.connectedIds().length), // Install automatically waits until no device is connected
    onShowModal: showUpdateWindow,
    notify: (title, body, onClick) => {
      if (!Notification.isSupported()) return;
      updateNote = new Notification({ title, body });
      updateNote.on('click', onClick);
      updateNote.show();
    },
  });
  updates.start();
  // TwinDesk Web (../web.js): the same server and pairings as the one-to-one app (one userData).
  web = require('../web').setupWeb({ deck: (bus) => (loadDeck() ? deck.web(bus) : null), settings: () => settings, save: saveSettings, pushState, t, device: () => device, helper, smb, notifs, fileClip,
    kvm: () => kvm, devctl: () => devctl });
  historyKeeper = new (require('../../shared/histkeeper.js').HistoryKeeper)({ dir: app.getPath('userData'), clip, notifs, changed: pushState });
  loadCamera(); // only while it's on
  loadReZume(); // only while it's on
  if (settings.drive.on || (settings.drive.folders || []).length) loadDrive(); // Drive, or shared folders
  require('../../shared/drive-wake.js').driveWake((t, fn) => hub.bus.on(t, fn), () => drive, loadDrive); // a computer's shared folder offered here
  // Shared folders (shared/folders-host.js): the File Sharing card, and the sheet the file manager's Share folder opens.
  folders = require('../../shared/folders-host.js').foldersHost({
    settings: () => settings, save: saveSettings, push: pushState, getDrive: () => drive, folders: () => folders, loadDrive,
    phoneShare: () => { const h = phoneHub || (phoneLink ? loadHub() : null); return h && h.share; },
    devices: () => (hub ? hub.peers({ indirect: true }) : []).map((d) => ({ id: d.id, name: d.name, os: d.os, connected: d.state === 'connected' })),
    pick: async () => { const r = await require('electron').dialog.showOpenDialog(mainWin, { properties: ['openDirectory', 'createDirectory'] }); return r.canceled ? '' : r.filePaths[0] || ''; },
    show: () => goTab('files'),
    open: (f) => require('electron').shell.openPath(f),
  });
  const ipc = setupIpc({ showFileShelf, batteryAlerts, iosScreen: (pid) => {
    const k = hub.mesh.known().find((x) => x.id === pid);
    console.log(`[relay] show ${pid}: ${JSON.stringify((ios && ios.cableFor(pid)) || (android && android.cableFor(pid)) || null)}`);
    return !!(phone && phone.first.views.openCable(pid, (k && k.name) || (k && k.os === P.OS.ANDROID ? 'Phone' : 'iPhone')));
  }, dbg: () => dbg, loadDrive,
    takePhoto: () => !!phonePhoto && phonePhoto.take(),
    scanDocument: () => !!phonePhoto && phonePhoto.scan(), getDrive: () => drive, folders: () => folders, history: (r) => historyKeeper && historyKeeper.act(r), get fileRecv() { return fileRecv; }, clearFiles: () => { fileDrop.last = null; if (fileDrop && fileDrop.sent) fileDrop.sent.length = 0; if (fileRecv) { fileRecv.last = null; if (fileRecv.clearRecent) fileRecv.clearRecent(); } if (kvm && kvm.dragRecv) kvm.dragRecv.last = null; pushState(); }, // Files › Recent › Clear: only the list
    devctl: () => devctl, chats: () => chats, consent: () => consent, edges: () => edges, pairSync: () => pairSync, termNames: () => termNames, mgr: () => mgr, padShare: () => padShare, ownSound: () => ownSound, viewers: () => viewers, qrPair: qrPairView, adbQr: adbQrDo, hub, link, discovery, screen, clip, kvm, layoutSync, fileDrop, smb, fileClip, vdd, sound, pcScreen, notifs, wake, terminal, sshd, apps, pcApps, peerApps, updates, settings, save: saveSettings, push: pushState, buildState,
    get phone() { return phone; }, get phoneViews() { return phone ? phone.views : null; }, get camShare() { return camShare; }, iosSign: () => iosSign, deck: () => loadDeck(), get phoneRemote() { return phoneRemote && phoneRemote.loaded ? phoneRemote : null; }, loadRemote, get rezume() { return rezume; }, loadReZume, rezumeWith: (id) => rzSolo && rzSolo.choose(id), get vcam() { return vcam; }, setCamera, setCameraFrom, get phoneDrive() { return phoneDrive; }, get nowPlaying() { return nowPlaying; }, get btAudio() { return btAudio; }, loadNowPlaying: () => nowPlaying, loadBtAudio, connectPhoneDev, cancelPhoneInvite, phoneHub: loadHub, loadMic,
    applyMesh: () => autoJoin && autoJoin.schedule(),
    get proximityLock() { return proximityLock; },
    get net() { return net; }, get wifi() { return wifi; }, applyNet, joinHotspot, openBluetoothSettings,
    checkFirewall, fixFirewall, fixInput, leaveInputGroup, removeInput, setStartup, onApp: () => { updateTray(buildState()); applyLocalApi(); if (awake) awake.update(); }, onLanguage: changeLanguage, onLook: () => theme.setPref(settings.ui.theme) });
  // Two-way switches per pair (shared/pairsync-mesh.js): every device's pair on its own session; the
  // settings hold the pair of the device the pages show (no ReZume or Remote here).
  {
    const { VALUES } = require('../pairsync');
    const only = ['clipboard', 'notifs', 'apps', 'audio', 'cursor', 'terminal', 'files'];
    const features = Object.fromEntries(Object.entries(PAIR_FEATURES).filter(([f]) => only.includes(f)));
    pairSync = require('../../shared/pairsync-mesh.js').pairSyncMesh({
      bus: hub.bus, hub, features, values: VALUES, settings: () => settings, save: saveSettings,
      setFeature: (f, dir, on) => { const [sec, key] = features[f][dir]; ipc.set(sec, { [key]: on }); },
      setValue: (k, v) => { const [sec, key] = VALUES[k].path; ipc.set(sec, { [key]: v }); },
      peerRole: (id) => { const x = hub.sessions.get(id); return x ? x.role : null; },
      peerOs: (id) => { const x = hub.sessions.get(id); return x ? x.peerOs : null; },
      onPair: (pid) => consent.changed(pid),
      onAsk: () => pushState(), // a computer asks for a shell here: the Terminal page answers
    });
  }
  // The whole mesh's two-way switches, every device telling the others (shared/mesh-edges.js): the
  // Multi-device tab's matrix. The features whose pair each device's features read (shared/consent.js).
  edges = require('../../shared/mesh-edges.js').meshEdges({
    bus: hub.bus, mesh, selfId: device.id, consent,
    features: ['clipboard', 'notifs', 'audio', 'files', 'cursor', 'terminal', 'apps'].map((key) => ({ key, dirs: { out: !!PAIR_FEATURES[key].out, in: !!PAIR_FEATURES[key].in } })),
    names: (pid) => (pid === device.id ? device.name : ((hub.peers({ indirect: true }).find((x) => x.id === pid) || {}).name || '')),
    os: (pid) => (pid === device.id ? P.OS.LINUX : ((hub.peers({ indirect: true }).find((x) => x.id === pid) || {}).os || '')),
    connected: (pid) => { const x = hub.sessions.get(pid); return !!x && x.connected; },
  });
  // Drop (shared/drop.js): one conversation with every TwinDesk device, through this app's links.
  if (!modulesAtStart.includes('drop')) drop = require('../../shared/drop-host.js').start({ selfId: device.id, name: () => device.name, os: P.OS.LINUX, settings: () => settings, save: saveSettings, push: pushState, hub }, () => mainWin);
  // The mesh's computers for a phone, read only (shared/mesh-view.js): names, connected, a laptop's battery.
  meshView = require('../../shared/mesh-view.js').onHub({ hub, mesh, selfId: device.id, name: () => device.name, os: P.OS.LINUX, devLocal: devctl.local, onChange: pushState });
  // Controller sharing (Camera & Controller, shared/pad-share.js): this computer's controller on another, or theirs here.
  padShare = new (require('../../shared/pad-share.js').PadShare)({
    send: (to, m) => hub.bus.send(to, m), on: (t, fn) => hub.bus.on(t, fn), connected: (to) => hub.bus.connectedIds().includes(to),
      devices: () => hub.peers({ indirect: true }), // the computers it can be shared with
      lane: (to) => { const s = hub.sessions && hub.sessions.get(to); return (s && s.lane && s.lane()) || null; }, // the UDP input lane, when up
    getSettings: () => settings, save: saveSettings, loadPad: () => require('../gamepad'), onChange: pushState,
  });
  hub.bus.onPeer('welcome', (pid) => padShare && padShare.hello(pid)); // our controller's offer, if it's shared with it
  // Mesh managers (docs/mesh.md, shared/mesh-mgr.js): this computer is managed only by a manager it
  // accepted, for what it accepted; it can be one itself only in TwinDesk Professional (the Full KVM build).
  mgr = require('../../shared/mesh-mgr.js').onHub({
    hub, mesh, selfId: device.id, name: () => device.name, settings: () => settings, save: saveSettings, devLocal: devctl.local,
    onChange: () => { // and a grant for Biometric unlock reaches the Full KVM side at once
      pushState();
      const k = JSON.stringify(((settings.mgr || {}).grants) || {});
      if (k !== mgrGrants) { mgrGrants = k; if (require('../../shared/edition.js').fullKvm()) require('../fullkvm/manager.js').unlockChanged(); }
    },
    wake: (id) => !!(wake && wake.wake(id)), wakes: () => Object.keys(((settings.wake || {}).peers) || {}),
  });
  nativeTheme.on('updated', pushState);
  link.start();
  hub.bus.onPeer('welcome', (pid) => { // a Mac app's launcher was used while the Mac wasn't connected: a Mac connects
    const x = hub.sessions.get(pid);
    if (!pendingMacApp || !x || x.peerOs !== P.OS.MAC) return;
    if (Date.now() < pendingMacApp.until) openMacApp(pendingMacApp.id);
    pendingMacApp = null;
  });

  createTray();
  createMainWindow();
  if (!sendTo.handle(process.argv) && !shareFolderArg(process.argv)) openMacAppArg(process.argv);
  checkFirewall();
  if (process.argv.includes('--test-monitor')) screen.open(true); // dev: ?test=1 pattern
}

// The Wayland backend can't ask the compositor for the monitors: tell it ours (logical px).
let sentScreens = '';
function sendScreens() {
  if (!helper || (helper.kvmBackend || helper.backend) !== 'uinput') return; // ours on Wayland, or the Full KVM service's
  const { screen: displays } = require('electron');
  const primary = displays.getPrimaryDisplay().id;
  const list = displays.getAllDisplays().map((d) => [d.bounds.x, d.bounds.y, d.bounds.width, d.bounds.height, d.id === primary ? 1 : 0].join(',')).join(';');
  // In the log once per change: where the pointer may go is only what this says (#183).
  if (list !== sentScreens) console.log('[kvm] Wayland monitors (x,y,w,h,primary):', list);
  sentScreens = list;
  helper.send('screens', { list });
}

// Host role (L4): our own server, once the certificate exists (made on first start).
async function startHost(tries = 0) {
  try {
    const id = await identity.load();
    if (quitting) return;
    discovery.self.fp = id.fp; // beacons carry it now
    const server = new Server(id);
    if (taskAlerts) taskAlerts.attach(server); // the phones of this computer (Local API › task alerts)
    discovery.self.port = server.port;
    const pairing = new HostPairing(server, { id: device.id, name: device.name, fp: id.fp });
    proximityLock = installProximityLock({ server, pairing, settings, i18n, onChange: pushState,
      occupied: (ctx) => ['asking', 'joining', 'hotspot'].includes(net?.state) ||
        (ctx.transport === 'ble' && (bleOff || net?.linked)),
    });
    pairing.on('request', showMain); // a code to compare: bring the window up
    hub.attachHost(server, pairing);
    hostServer = server;
    const livePhone = (ctx) => !quitting && ctx && ctx.authed !== false && ctx.released !== true
      && P.isPhoneOs(ctx.os) && server.clients.get(ctx.deviceId) === ctx && hub.sessions.get(ctx.deviceId)?.ctx === ctx;
    server.on('client', (ctx) => { if (livePhone(ctx)) batteryAlerts.begin(ctx); });
    server.on('closed', (ctx) => { if (ctx && P.isPhoneOs(ctx.os)) batteryAlerts.end(ctx); });
    server.on(`t:${P.T.PHONE_INFO}`, (msg, ctx) => { if (livePhone(ctx)) batteryAlerts.info(msg, ctx); });
    bleHost = new BleHost({
      helper, server,
      info: () => ({ id: device.id, name: device.name.slice(0, 40), os: P.OS.LINUX, port: server.port, fp: id.fp }),
      enabled: () => bleHostOn(),
      accept: (g) => bleAccepts(g.os),
      // Quiet on Wi-Fi with an iPhone or iPad in the session or linked: its link stays (the helper's bleHold).
      hold: () => blePhonesOn() && (iosNow() || bleHost.list().some((g) => g.os === P.OS.IOS)),
      // …but advertising until the iPhone or iPad in the session has linked (another device's link
      // kept it silent: an iPhone paired over Wi-Fi never found it, and fell back to nothing).
      holdAds: () => iosSessions().some((s) => !bleHost.list().some((g) => g.id === s.id)),
    });
    bleHost.on('change', pushState);
    discovery.extras.unshift(bleHost);
    blePhones = new BlePhones({ helper, server, hello: bleHost.info });
    blePhones.on('change', pushState);
    // A phone linked or gone: advertising follows (bleHostOn), after BlePhones has seen the event.
    helper.on('event', (name) => { if (name.startsWith('blp.')) bleHost.apply(); });
    setInterval(() => bleHost.apply(), 2000); // and a pipe our end closed (no event): apply() only compares when nothing changed
    // The phone asks for a pipe: it has none, so one still held for it is dead (an open that crossed
    // its "closed"), and BlePhones, seeing it, opened nothing: our TLS answer sat in it, the phone's
    // hello timed out. Before BlePhones sees the ask: that one goes (no "closed" to the phone), a fresh one comes.
    helper.prependListener('event', (name, m) => {
      const dev = name === 'blp.want' && String(m.dev || '').slice(0, 64);
      if (dev && blePhones.pipes.has(dev)) blePhones._closePipe(dev);
    });
    discovery.extras.push(blePhones);
    server.on('phoneFree', () => { for (const l of links.list()) l.poke(); pushState(); });
  } catch (e) {
    console.error('[host]', e.message);
    hub.hostFailed('No certificate: ' + e.message);
    if (tries < 5) setTimeout(() => startHost(tries + 1), 15000); // a busy computer at login: try again
    return;
  }
  // Outside the retry: the server already holds the port, a second one would only find it in use.
  try {
    startPhone(hostServer, hub.pairing);
  } catch (e) {
    console.error('[phone]', e.message);
  }
}

// A phone as the peer (port of the PC's): the sidebar tile and Phone page (phone.js), its screen,
// touch, mouse, keyboard and clipboard through wireless debugging (phone-bridge.js), and its
// screen and apps in windows here (phoneview.js). X11 and Wayland alike: the phone's input goes
// through adb, not the helper.
function startPhone(server, pairing) {
  const pl = new PhoneLink(hub, server);
  setupHub(pl);
  const adb = new Adb(); // one adb for every phone
  // A phone on a USB cable: pairing, the session, screen and sound through it (no Wi-Fi needed).
  wired = new Wired({ adb, raw: server, peer: pl, getId: () => device.id, getName: () => device.name,
    hasPhone: () => pairing.list().some((x) => P.isPhoneOs(x.os)) });
  pairing.isWired = (nonce) => wired.knows(nonce) || qrKnows(nonce); // the cable, or Connection's QR code (Allow only)
  pairing.isQr = qrKnows;
  pairing.consumeQr = () => { qrPair = null; }; // a QR pairing that went through: the link is single-use
  wired.on('change', pushState);
  // An iPhone's or iPad's session through its USB cable (shared/iosnet.js: usbmuxd to the app's port):
  // this server and the WebRTC relay (wired.js), nothing else.
  iosNet = new (require('../../shared/iosnet.js').IosNet)({
    getId: () => device.id, getName: () => device.name,
    allowed: (port) => port === server.port || port === wired.turnPort,
  });
  iosNet.on('change', () => { if (iosNet.view.devices.some((d) => d.app)) wired.relay(); pushState(); });
  // Every phone gets its own stack (phone.js, phone-bridge.js, phoneview.js) made on a link scoped to it
  // (phones.js); `phone` is also the single-phone API for the active one.
  // What plays on each phone (one shared/nowplaying.js per phone while Audio › Media controls is on),
  // and on this computer for each phone's Media page (shared/pcnow.js).
  nowPlaying = require('../../shared/perphone.js').phoneMedia({
    NowPlaying: require('../../shared/nowplaying.js').NowPlaying, cfg: () => settings.audio, onChange: pushState, phones: () => phone,
  });
  // Each phone's Remote page drives this computer (shared/phone-remote.js, one per phone), made once
  // Remote or Keyboard's voice typing is on; the Remote page shows the active phone's.
  phoneRemote = require('../../shared/perphone.js').phoneRemote({
    PhoneRemote: require('../../shared/phone-remote.js').PhoneRemote,
    opts: { helper, getSettings: () => settings, atHome: () => !kvm || kvm.mode === 'home', onChange: pushState, loadPad: () => require('../gamepad'), save: saveSettings },
    wanted: () => !!(settings.remote.allow || settings.kvm.keyboard),
    phones: () => phone,
  });
  // TwinDesk iPhone (shared/iossign.js): TwinDesk for iPhone signed with the person's Apple ID, for
  // whichever iPhone connected or spoke last. Off in General › Modules: not loaded.
  const anyPhone = require('../../shared/perphone.js').anyPhone({ want: (c) => c.os === P.OS.IOS }); // TwinDesk iPhone: one iPhone at a time
  if (!modulesAtStart.includes('iossign')) iosSign = require('../../shared/iossign-host.js').create({
    app, safeStorage: require('electron').safeStorage, link: anyPhone.link,
    near: { list: () => (bleHost ? bleHost.list() : []), invite: (devId) => bleHost && bleHost.invite(devId) }, // iPhones linked over Bluetooth
    usbSerials: () => (iosNet ? iosNet.view.devices.filter((x) => x.app).map((x) => x.serial) : []),
    onChange: pushState,
  });
  const { PcNow } = require('../../shared/pcnow.js');
  phone = new PhoneSet({
    hub, link: pl, raw: server, discovery, pairing, wired,
    make: (scoped) => {
      const ph = new Phone({ server: scoped, raw: server, discovery, pairing });
      const bridge = new PhoneBridge({ server: scoped, phone: ph, getSettings: () => settings, clipboard: clip, adb });
      ph.bridge = bridge;
      ph.wired = wired;
      bridge.wired = wired;
      const views = new PhoneViews({ bridge, phone: ph, getSettings: () => settings, server: scoped, fileSend: fileDrop });
      // On Wi-Fi after Bluetooth, wireless debugging takes a moment more: the window opens once it's up.
      views.onNoAdb = (v) => {
        const c = scoped.current;
        if (!c || c.os !== P.OS.ANDROID || !(c.transport === 'ble' || (net && net.linked))) return false;
        pendingView = { ...v, until: Date.now() + 60 * 1000 };
        if (net && net.onBle) net.need('phone').then((ok) => !ok && (pendingView = null));
        else hud.show('home', { key: 'Opening it when wireless debugging is ready…' });
        return true;
      };
      viaWifi(views, 'openScreen', 'phone');
      viaWifi(views, 'openApp', 'phone');
      return { phone: ph, bridge, views };
    },
    onUnit: (u) => {
      u.phone.on('change', () => layoutSync && layoutSync.phonesChanged()); // turned, or came and went: its tile on the map (#375)
      u.phone.on('change', pushState);
      if (vcam) u.views.vcam = vcam; // a phone's camera feeds the virtual camera too
      // The phone's Keyboard page names this computer's hotkey (double-tap = everything back here).
      u.link.on('client', () => u.link.sendToClient({ t: 'phone.mac', hotkey: P.hotkeyName(settings.keys.hotkey || P.HOTKEY_WIN, 'win').replace('Windows key', 'Super') }));
      u.bridge.on('save', saveSettings);
      u.bridge.on('change', () => {
        pushState();
        if (pendingView && u.bridge.serial) {
          const v = pendingView;
          pendingView = null;
          if (Date.now() < v.until) v.kind === 'app' ? u.views.openApp(v.app, v.title) : u.views.openScreen();
        }
      });
      u.bridge.on('popup', (kind, text) => hud.show(kind, text));
      u.views.on('change', pushState);
      u.views.on('focus', () => kvm.applyConfig());
      // A phone's screen through another computer: an iPhone on a USB cable, ours or another computer's
      // (shared/ios-mesh.js), an Android phone connected to another computer (shared/android-relay.js).
      u.views.makeRelay = (r) => (r.os === 'android' ? android && android.makeRelay(r) : ios && ios.makeRelay(r));
      u.views.cableFor = (pid) => (ios && ios.cableFor(pid)) || (android && android.cableFor(pid)) || null;
      u.views.onUsbScreen = (udid) => ios && ios.onUsbScreen(udid);
      nowPlaying.unit(u);
      phoneRemote.unit(u);
      anyPhone.unit(u);
      if (loadDeck()) deck.add(u.link); // that phone's Deck runs here
      const now = new PcNow({ server: u.link, key: (code) => {
        if (!helper) return;
        helper.send('inject', { ev: { t: P.T.K_KEY_DOWN, code } });
        helper.send('inject', { ev: { t: P.T.K_KEY_UP, code } });
      } });
      if (!pcNowRef) pcNowRef = now; // what plays here, for Calls › Pause what plays here (one is enough: it's this computer's)
    },
  });
  loadBtAudio();
  // A phone notification clicked here: its app in a window (on the phone it came from).
  notifs.onClick = (m) => {
    const u = phone.unit(m.originId);
    if (u && u.link.current) u.views.openNotified(m.app, m.appName);
  };
  // Camera › Take a photo / Scan document (shared/phonephoto.js): the active Android phone.
  {
    const { PhonePhoto, copyPicture } = require('../../shared/phonephoto.js');
    const phoneOn = () => require('../../shared/phonephoto.js').canCapture(phone.active.link.current, phone.info); // Android, or an iPhone that can
    phonePhoto = new PhonePhoto({
      send: (m) => phone.active.link.sendToClient(m),
      phoneOn,
      popup: (key, vars) => hud && hud.show('driven', { key, vars }),
      copy: (f) => copyPicture(require('electron'), f),
    });
    pl.on('t:cam.capture', (m) => { if (m && m.on === false) phonePhoto.ended(); });
    pl.on('closed', () => { if (phonePhoto && !phoneOn()) phonePhoto.ended(); }); // a phone left, and no Android remains
  }
  // Mount: the active phone's storage as a drive here (it was never made, so Mount did nothing, #259).
  phoneDrive = new PhoneDrive({ adb, bridge: phone.bridgeProxy, phone });
  phoneDrive.on('change', pushState);
  kvm.local = phone; // driving a phone goes through adb, by the partner: phone.drives(id) / handle(msg, id)
  kvm.blockEdge = (side) => phone.blocksEdge(side); // moving inside the phone window never crosses
  // An iPhone with the app on a USB cable (shared/ios-mesh.js): linked to its app once, known to the
  // whole mesh, its screen through the cable on any computer (ours, or another's through it).
  ios = require('../../shared/ios-mesh.js').iosMesh({
    hub, iosNet,
    store: { get: () => settings.iosLinks || {}, set: (l) => { settings.iosLinks = l; saveSettings(); } },
    dir: require('path').join(app.getPath('userData'), 'ios-ddi'),
    borrow: (udid) => { for (const u of phone.all) { const s = u.views.usbSession(udid); if (s) return s; } return null; },
    onChange: pushState,
  });
  // The Android phones connected here, their screen for the computers of the mesh; theirs here.
  android = require('../../shared/android-relay.js').androidRelay({
    hub,
    phones: () => phone.all.filter((u) => u.link.current && u.link.current.os === P.OS.ANDROID).map((u) => ({
      id: u.link.current.deviceId, name: u.link.current.name,
      hold: (on) => u.bridge.relayHold(on), // adb up while another computer shows it
      ready: () => (u.bridge.serial && u.bridge.state === 'ready' ? { adb: u.bridge.adb, serial: u.bridge.serial, opts: u.bridge.sessionOpts('screen') } : null),
      why: () => u.bridge.message,
    })),
    Session: require('../scrcpy').Session,
    KeyState: require('../android-keys').KeyState,
    onChange: pushState,
  });
  pushState();
}

// Calls, Messages, Photos and Files from a phone (shared/phonehub.js): loaded when a phone connects with
// one of them on, or the first time a page uses it. Before that none of it exists: no module, no
// listener, nothing sent to the phone. The call window (shared/callwin.js) only with a call.
let phoneHub = null;
let phoneLink = null; // phone-link.js, the phones' sessions (startPhone)
let callwin = null;
function setupHub(pl) {
  phoneLink = pl;
  const anyOn = () => settings.hub.calls || settings.hub.messages || settings.hub.media || settings.hub.files || settings.hub.shareServe || settings.hub.tether || settings.hub.phoneNet || !!(settings.drive.folders || []).length; // shared folders: the phone's are served
  pl.on('client', (ctx) => P.isPhoneOs(ctx.os) && !phoneHub && anyOn() && loadHub());
  // The phone shares a folder: loaded for it (its listener comes with it, so this one passes it on).
  pl.on(`t:${P.T.SHARE_OFFER}`, (m, ctx) => ctx && P.isPhoneOs(ctx.os) && !phoneHub && loadHub().share && phoneHub.share.onOffer(m));
  pl.on(`t:${P.T.SHARE_SET}`, (m, ctx) => ctx && P.isPhoneOs(ctx.os) && !phoneHub && loadHub().share && phoneHub.share.act('serve', { on: !!m.serve }));
  pl.on('t:tether.state', (m, ctx) => ctx && ctx.os === P.OS.ANDROID && m.can === true && !phoneHub && loadHub().tether && phoneHub.tether._state(m)); // a phone that can take Internet over USB (shared/tether.js)
  pl.on('t:phonenet.state', (m, ctx) => ctx && ctx.os === P.OS.ANDROID && m.can === true && !phoneHub && loadHub().phoneNet && phoneHub.phoneNet._state(m)); // a phone that can share its internet (shared/phonenet.js)
}

// Share this folder from the file manager's menu (shared/foldermenu.js): `--td share <folder>`.
function shareFolderArg(argv) {
  const dir = FolderMenu.fromArgv(argv);
  if (dir === null) return false;
  if (dir && settings) shareFolder(dir);
  return true;
}

function shareFolder(dir) {
  if (folders) folders.ask(dir); // the sheet: which devices (shared/folders-host.js)
}

function loadHub() {
  if (phoneHub || !phoneLink) return phoneHub || { act() {} };
  const { PhoneHub } = require('../../shared/phonehub.js');
  // One phone at a time, the active one, kept while it has a call (shared/phonehub-link.js, step 4).
  const hubLink = require('../../shared/phonehub-link.js').hubLink({
    phones: phoneLink, ctxOf: (id) => phoneLink.ctxOf(id), sendTo: (id, m) => hub.bus.send(id, m), held: () => !!(phoneHub && phoneHub.call),
  });
  phoneHub = new PhoneHub({
    server: hubLink, getSettings: () => settings, save: saveSettings,
    audio: (opts) => require('../callaudio.js').create({ helper, ...opts }), // the calls' sound over Bluetooth
    btSettings: openBluetoothSettings, // pairing the phone for the calls' sound
    send: (paths, batch) => !!(fileDrop && fileDrop.sendBatch(paths, 'send', batch)), // Files: into a folder on the phone
    choose: () => require('electron').dialog.showOpenDialog(mainWin && !mainWin.isDestroyed() ? mainWin : undefined, { properties: ['openFile', 'multiSelections'] }) // files only: with folders too it picks only folders here
      .then((r) => (r.canceled ? [] : r.filePaths)),
    tether: { adb: phone && phone.bridge && phone.bridge.adb, cableSerial: (id) => wired && wired.cableSerial(id) }, // Internet over USB (shared/tether.js)
    phoneNet: { sysProxy: require('../../shared/phonenet.js').systemProxy({ run: require('../../shared/phonenet.js').runSync }), stateFile: path.join(app.getPath('userData'), 'phonenet-proxy.json') }, // the phone's internet here (shared/phonenet.js, #361)
    // Photo backup (Photos › settings, off): loaded only while it's on (shared/photo-backup.js).
    backup: {
      file: path.join(app.getPath('userData'), 'photo-backup.json'), pictures: app.getPath('pictures'), receiver: () => fileRecv,
      trash: (p) => require('electron').shell.trashItem(p), reveal: (d) => require('electron').shell.openPath(d),
      chooseFolder: () => require('electron').dialog.showOpenDialog(mainWin && !mainWin.isDestroyed() ? mainWin : undefined, { properties: ['openDirectory', 'createDirectory'] }).then((r) => (r.canceled ? '' : r.filePaths[0])),
    },
    share: { // shared folders with the phone (shared/foldershare.js)
      mounter: require('../phonedrive').mounter, adb: phone && phone.bridge && phone.bridge.adb, serialOf: (id) => wired && wired.serialOf(id),
      chooseFolder: () => require('electron').dialog.showOpenDialog(mainWin && !mainWin.isDestroyed() ? mainWin : undefined, { properties: ['openDirectory', 'createDirectory'] }).then((r) => (r.canceled ? '' : r.filePaths[0])),
      defaultFolder: path.join(os.homedir(), 'MacShare'),
      tls: () => hostServer && hostServer.tls, // served with the session's certificate, which the phone pinned
      wifi: (on) => (!net ? Promise.resolve(false) : on ? net.need('folder') : Promise.resolve(net.release('folder'))), // through Bluetooth
    },
  });
  phoneHub.on('asked', () => { if (fileRecv) fileRecv.askedSends(); }); // its files come back as a Send (#239)
  phoneHub.on('change', pushState);
  phoneHub.on('data', (m) => mainWin && !mainWin.isDestroyed() && mainWin.webContents.send('hub', m));
  const popup = () => {
    if (!callwin && !phoneHub.call) return;
    callwin = callwin || require('../../shared/callwin.js');
    callwin.update(phoneHub, { corner: 'top', open: goTab, getLanguage: () => i18n.locale });
  };
  phoneHub.on('call', popup);
  // Calls › Pause what plays here: what plays on this computer pauses for a call (shared/callpause.js, #293).
  const callPause = new (require('../../shared/callpause.js').CallPause)({ media: () => pcNowRef && pcNowRef.media, on: () => settings.hub.callPause === true });
  phoneHub.on('call', (c) => callPause.onCall(c));
  phoneHub.on('change', popup);
  phoneHub.on('call', () => hubLink.refresh()); // a call that ended lets it go to the active phone
  hub.on('change', () => hubLink.refresh()); // a phone selected
  if (hubLink.current) phoneHub.started();
  return phoneHub;
}

// ---- not on the same network: Bluetooth, and Wi-Fi when it's needed ----

// The session through Bluetooth (blepipe.js, the helper's ble.c on BlueZ) when the other device
// isn't on this network; files and screens move it onto a Wi-Fi network one side hosts
// (netlink.js). This computer hosts an access point while its Wi-Fi isn't on a network, else joins
// the other side's (wifi.js, NetworkManager). Nothing here runs with a device that doesn't know
// about it: those never come through Bluetooth.
function setupNet() {
  // No BleGuest (a computer reached through Bluetooth): with Multi-device, computers connect to this one
  // over the network only (docs/multi-device.md). Phones still come through Bluetooth (BleHost, BlePhones).
  wifi = new Wifi({ keepWifi: () => settings.net.keepWifi, onChange: pushState });
  // What this computer can do (a Wi-Fi adapter plugged in, its Wi-Fi on a network or not): the other side hears when it changes.
  const recheck = () => wifi.refresh().then((changed) => changed && net.caps(), () => {});
  helper.on('ready', () => {
    applyNet();
    recheck();
  });
  // Bluetooth LE links that survive a phone or a Mac busy with Wi-Fi (wifi.js bleTimeout); again
  // now and then: a Bluetooth adapter that resets gets the kernel's default back.
  const bleTimeout = () => wifi.bleTimeout().catch(() => {});
  setTimeout(bleTimeout, 3000);
  setInterval(bleTimeout, 60000).unref();
  // The net hook's own link (not the facade): the selected device's, kept while Wi-Fi is being set up or
  // used for it, so a crossing doesn't cut a transfer through the network it was moved onto (hub.netId).
  const netLink = require('../../shared/scoped-link.js').scopedLink(hub, null);
  hub.netId = null;
  // Each device's last net.caps (what it can do to leave Bluetooth): the hook gets it when it binds there.
  const netCaps = new Map();
  hub.bus.on(P.T.NET_CAPS, (m, from) => netCaps.set(from, m));
  hub.bus.onPeer('closed', (id) => netCaps.delete(id));
  net = new NetLink({
    os: P.OS.LINUX,
    send: (m) => !!netLink.id && hub.bus.send(netLink.id, m),
    current: () => netLink.current,
    host: {
      can: () => wifi.canHost(netLink.current && netLink.current.os),
      start: (ssid, pass) => wifi.host(ssid, pass),
      stop: () => { proximityLock?.wifiDown(); return wifi.unhost(); },
    },
    join: {
      can: () => wifi.can(),
      start: (ssid, pass) => wifi.join(ssid, pass),
      stop: () => { proximityLock?.wifiDown(); return wifi.leave(); },
    },
    band5: () => wifi.band5,
    // Connect with hotspot (a phone): it switches its hotspot on, this computer joins it (the Overview asks
    // for its name and password once; joinHotspot).
    hotspot: (why, peerOs) => peerOs === P.OS.ANDROID && why === 'hotspot',
    cable: () => {
      const c = netLink.current;
      return !!c && c.os === P.OS.ANDROID && !!wired && wired.toCable(c.deviceId);
    },
  });
  net.on('change', pushState);
  net.on('dropped', () => pcScreen.mode !== 'off' && pcScreen.setMode('off')); // Back to Bluetooth on the phone: it can't carry the screen
  hub.netHold = (m) => net.holdOut(m, (x) => !!netLink.id && hub.bus.send(netLink.id, x)); // files wait for Wi-Fi (netlink.js)
  netLink.fx.active = () => net.touch('files'); // fast files on a link made for them keep it up, as file.chunk does
  hub.netTap = (m) => net.onMessage(m); // every message of the net hook's device (net.*)
  const netUp = () => {
    net.started();
    recheck();
    applyBle();
  };
  const netDown = () => {
    bleEnded = Date.now(); // Bluetooth looks a while, window or not: the session comes back by itself
    net.ended();
    applyBle();
  };
  // Bound to a device: the selected one, unless it's busy with another (hosting, joining, asking).
  const bindNet = (id) => {
    if (netLink.id === id) return;
    if (netLink.id && netLink.current) netDown();
    netLink.bind(id);
    hub.netId = id;
    if (id && netLink.current) netUp();
    if (id && netCaps.has(id)) net.onMessage(netCaps.get(id));
  };
  const netBusy = () => ['asking', 'hosting', 'joining', 'joined', 'hotspot'].includes(net.state); // Wi-Fi up or on its way for it
  hub.on('selected', (id) => { if (!netBusy() || !netLink.current) bindNet(id || null); });
  net.on('change', () => setImmediate(() => { if (!netBusy() && netLink.id !== (hub.selectedId || null)) bindNet(hub.selectedId || null); })); // done: the selection's again
  hub.bus.onPeer('welcome', (id) => { if (id === netLink.id) netUp(); else if (!netLink.current && id === hub.selectedId) bindNet(id); });
  hub.bus.onPeer('closed', (id) => {
    if (id !== netLink.id) return;
    netDown();
    if (hub.selectedId && hub.selectedId !== id) bindNet(hub.selectedId);
  });
  hub.bus.onPeer('transport', (id) => {
    if (id !== netLink.id) return;
    applyBle(); // on Wi-Fi or a cable now: no more looking, the Bluetooth fallback stays
    pushState();
    screen.policy();
    if (!net.onBle && settings.files.mountMac && smb.mac && !smb.mounted) smbMount(); // on Wi-Fi now: the folder too
  });
  bindNet(hub.selectedId || null);
  // The other computer's folder through Bluetooth: not connected there (its address is the pipe's);
  // Open moves the session onto Wi-Fi Direct and connects it then, kept up while it's connected.
  const smbMount = () => smb.mountNow();
  let smbWait = false;
  // Each device's folder waits for Wi-Fi while that device is reached through Bluetooth (shared/smb-mesh.js).
  smb.canMount = (id) => { const s = hub.sessions.get(id); return !(s && s.transport === 'ble'); };
  smb.openOverWifi = () => {
    if (smbWait) return;
    smbWait = true;
    waitWifi('smb', () => smbMount().then(() => {
      smbWait = false;
      smb.open();
    }), () => { smbWait = false; });
  };
  // Screens wait for Wi-Fi (WebRTC over Bluetooth would never work); each lets go when it closes.
  const policy = screen.policy.bind(screen);
  let screenWait = false;
  screen.policy = () => {
    if (!net.onBle || !screen.watching()) return policy();
    if (screenWait) return;
    screenWait = true;
    waitWifi('screen', () => { screenWait = false; policy(); }, () => { screenWait = false; });
  };
  const setMode = pcScreen.setMode.bind(pcScreen);
  pcScreen.setMode = (mode) => (mode !== 'off' && net.onBle ? waitWifi('share', () => setMode(mode)) : setMode(mode));
  viaWifi(peerApps, 'launch', 'apps');
  viaWifi(apps, 'launch', 'apps');
  setInterval(() => {
    if (!screen.watching()) net.release('screen');
    if (pcScreen.mode === 'off') net.release('share');
    if (!peerApps.view().open && !screen.watching()) net.release('apps');
    if (!(phone && phone.views && phone.views.list().length) && !pendingView) net.release('phone');
    if (!smb.mounted && !smbWait) net.release('smb');
    applyBle();
    inviteIos();
  }, 2000);
  setInterval(lookForPhones, PHONE_LOOK_MS);
  const refresh = discovery.refresh.bind(discovery);
  discovery.refresh = () => { // Refresh: phones nearby answer again too
    refresh();
    lookForPhones();
  };
}

// Bluetooth, two switches (General): with phones (on unless switched off) and with computers (off
// unless switched on). Advertising runs the whole time either is on, sessions on Wi-Fi or a cable
// included: the Bluetooth fallback stays beside them, and the session goes back to it when the
// network ends. Looking for devices (scanning) only while there's no session and the window is
// open, or one just ended (shared/blepolicy.js).
let bleEnded = 0; // when the last session ended
const blePhonesOn = () => settings.net.ble !== false;
const blePcsOn = () => false; // Multi-device: computers over the network only, whatever General says (docs/multi-device.md)
function bleNow() {
  return blePolicy({ enabled: () => blePhonesOn() || blePcsOn(), windowOpen: () => !!mainWin && !mainWin.isDestroyed() && mainWin.isVisible(), current: () => link.current, ended: bleEnded });
}

// Who may come in through our advertising: a phone with phones on, a computer with computers on.
function bleAccepts(os) {
  return P.isPhoneOs(os) ? blePhonesOn() : blePcsOn();
}

function bleHostOn() {
  if (bleOff || !(blePhonesOn() || blePcsOn())) return false;
  // Linked to a phone ourselves (BlePhones): not while no computer needs it. Seeing us advertise, the
  // phone connected over that same link to read who we are, and closing its side again made Android
  // drop the whole link, ours too: the phone's session went every few seconds to half a minute. It
  // asks for a pipe through our link (blp.want) without seeing us advertise.
  const pc = !!bleHost && ([...bleHost.guests.values()].some((g) => !P.isPhoneOs(g.os)) || bleHost.pipes.size > 0);
  return !(blePhones && blePhones.links.size > 0 && !pc);
}

function applyBle() {
  applyQuiet(bleQuiet({ on: settings.net.bleWifiOff, current: () => link.current, onGroup: () => !!net && net.onGroup }));
  const p = bleNow();
  if (bleHost) bleHost.apply();
  if (bleOff) {
    if (bleGuest) bleGuest.drop();
    if (blePhones) blePhones.stop();
    return;
  }
  if (bleGuest) bleGuest.scan(p.look && blePcsOn());
  if (blePhones) {
    if (!blePhonesOn()) {
      blePhones.stop();
      return bleHost.apply(); // no phone links now: advertising for computers may come back
    }
    blePhones.autoLink = p.look; // in a session: phones found are listed, linked only on Pair or Connect
    blePhones.scan(p.look);
    if (!p.look && !p.hold) blePhones.trim(); // links without a pipe; the session's and its fallback stay
    bleHost.apply(); // links trimmed: advertising may come back (bleHostOn)
  }
}

// iPhones and iPads in a session (their Bluetooth link is held through quiet: BleHost hold).
const iosSessions = () => (hub ? hub.sessions.list().filter((s) => s.connected && s.peerOs === P.OS.IOS) : []);
const iosNow = () => iosSessions().length > 0;

// An iPhone or iPad linked over Bluetooth but not in a session (it links only to computers it's
// paired with): invited now and then, which wakes TwinDesk there to come back (its Ble.swift).
let iosInvitedAt = 0;
function inviteIos() {
  if (!bleHost || bleOff || Date.now() - iosInvitedAt < 20000) return;
  const on = new Set(iosSessions().map((s) => s.id));
  for (const g of bleHost.list()) {
    if (g.os !== P.OS.IOS || on.has(g.id)) continue;
    iosInvitedAt = Date.now();
    bleHost.invite(g.id);
  }
}
// The session on the same Wi-Fi a while (General's Turn off Bluetooth on Wi-Fi connections,
// blepolicy.js wifiQuiet): no advertising, scanning or links, its Bluetooth fallback closed with
// them; back as it was when the session ends.
function applyQuiet(off) {
  if (off === bleOff) return;
  bleOff = off;
  if (off) proximityLock?.bluetoothOff();
  console.log(`[ble] ${off ? 'off: the session is on the same Wi-Fi' : 'on again'}`);
  pushState();
}

// Phones advertise while they're open and not connected: with this window open we look for them
// now and then (PHONE_LOOK_MS) and on Refresh, in a session too (listed under Found nearby, nothing
// linked until Pair or Connect). Not while the window is closed, nor while a phone's session runs on
// Bluetooth: the phone advertises under a new address now and then, and found there it counted as
// moved, its link (the session's) dropped for the new one.
const PHONE_LOOK_MS = 5000;
const PHONE_BURST_MS = 2000;
function lookForPhones() {
  if (!blePhones || !blePhonesOn() || bleOff || !mainWin || mainWin.isDestroyed() || !mainWin.isVisible()) return;
  const c = link.current;
  if (c && P.isPhoneOs(c.os) && c.transport === 'ble') return;
  blePhones.burst(PHONE_BURST_MS);
}

// Bluetooth on or off (General), or the helper restarted.
function applyNet() {
  applyBle();
  pushState();
}

// The phone's saved hotspot, for the Overview's form.
function hotspotView() {
  const c = link.current;
  const h = c && settings.net.hotspots[c.deviceId];
  return { hotspotSsid: h ? h.ssid : '', hotspotSaved: !!(h && h.pass) };
}

// The phone's hotspot is on: join it, remembered for that phone (the password field empty = the saved one).
function joinHotspot(arg) {
  const { safeStorage } = require('electron');
  const c = link.current;
  const ssid = String((arg && arg.ssid) || '').trim().slice(0, 32);
  let pass = String((arg && arg.pass) || '').slice(0, 63);
  if (!ssid || !c || !net) return;
  const saved = settings.net.hotspots[c.deviceId];
  if (!pass && saved && saved.ssid === ssid && saved.pass) {
    try { pass = safeStorage.decryptString(Buffer.from(saved.pass, 'base64')); } catch (_) { /* another user's, or the keyring gone */ }
  }
  const sealed = pass && safeStorage.isEncryptionAvailable() ? safeStorage.encryptString(pass).toString('base64') : '';
  settings.net.hotspots[c.deviceId] = { ssid, pass: sealed };
  saveSettings();
  net.joinHotspot(ssid, pass);
}

// Settings › Bluetooth of whichever desktop this is.
function openBluetoothSettings() {
  const tries = [['gnome-control-center', ['bluetooth']], ['cinnamon-settings', ['bluetooth']], ['blueman-manager', []],
    ['systemsettings', ['kcm_bluetooth']], ['blueberry', []], ['xfce4-settings-manager', []]];
  const next = (i) => {
    if (i >= tries.length) return;
    const p = spawn(tries[i][0], tries[i][1], { detached: true, stdio: 'ignore' });
    p.on('error', () => next(i + 1));
    p.unref();
  };
  next(0);
}

// fn once the session is on Wi-Fi (now, if it isn't on Bluetooth); a popup if it can't be.
function waitWifi(why, fn, failed) {
  if (!net || (!net.onBle && !net.linked)) return fn();
  if (!net.onBle) return void net.need(why).then(fn); // on a link made for something else: kept up for this too
  hud.show('home', { key: 'Moving to Wi-Fi with {name}…', vars: { name: peerName() } });
  net.need(why).then((ok) => {
    if (ok) return fn();
    hud.show('home', net.error || { key: 'Wi-Fi with {name} didn’t come up', vars: { name: peerName() } });
    if (failed) failed();
  });
}

// obj[method] waits for Wi-Fi first.
function viaWifi(obj, method, why) {
  const orig = obj[method].bind(obj);
  obj[method] = (...args) => waitWifi(why, () => orig(...args));
}

// A phone found nearby: a paired one is asked to connect, any other to pair with this computer.
// An unpaired one: the popup says Pair has to be pressed on it, until it starts pairing or a minute went by.
let phoneInvite = null; // {id, name, until}
function connectPhoneDev(d) {
  proximityLock?.cancel();
  discovery.clearInvite(d.id);
  const paired = phone && link.pairing && link.pairing.list().some((p) => p.id === d.id);
  if (!paired) {
    phoneInvite = { id: d.id, name: d.name, until: Date.now() + 60 * 1000 };
    setTimeout(pushState, 61 * 1000);
    pushState();
  }
  if (String(d.address).startsWith('ble:')) return discovery.invite(d.address); // near over Bluetooth only (BlePhones)
  if (paired) phone.connect(d.id);
  else discovery.invite(d.address);
}
function phoneInviteView(s) {
  if (phoneInvite && (Date.now() > phoneInvite.until || s.pairing || (s.peer && s.peer.id === phoneInvite.id))) phoneInvite = null;
  return phoneInvite && { name: phoneInvite.name };
}
function cancelPhoneInvite() {
  phoneInvite = null;
  pushState();
}

// ---- Mac apps from their launchers ----

function openMacAppArg(argv) {
  const arg = (argv || []).find((a) => typeof a === 'string' && a.startsWith('--mac-app='));
  if (!arg) return false;
  const id = arg.slice('--mac-app='.length).slice(0, 1024);
  if (id) openMacApp(id);
  return true;
}

function openMacApp(id) {
  if (link.snapshot().link.state === 'connected' && link.peerOs === P.OS.MAC) {
    apps.launch(id);
    screen.ensureHidden(); // the app windows come from the Mac's screen stream
  } else {
    pendingMacApp = { id, until: Date.now() + 2 * 60 * 1000 };
    if (hud) hud.show('home', { key: 'Opening it when {name} connects…', vars: { name: peerName() } });
  }
}

// ---- state ----

let pushQueued = false;
// Queued: one state push per tick. It never throws (an exception here became an Electron error
// dialog, or a window that stopped updating): a failure is logged and the next push tries again.
function applyLocalApi() {
  if (!localApi) return;
  if (!settings.app.localApi && taskAlerts) taskAlerts.clear(); // no watch outlives the API
  localApi.apply(!!settings.app.localApi).catch((e) => console.error('[api] ' + e.message)).then(() => pushState());
}

let jumpKeys = null; // jump shortcuts at home
// File Shelf (shared/file-shelf.js): the last files received, opened from the tray or Files › Recent.
// view 'recent' (the tray, Files › Recent) or 'shelf'; at: under the pointer (a shaken file drag).
function showFileShelf(o = {}) {
  if (!fileRecv || modulesAtStart.includes('files')) return;
  fileShelf ||= new (require('../../shared/file-shelf.js').FileShelves)({ recent: () => (fileRecv && fileRecv.recent) || [], t,
    devices: () => (hub ? hub.peers().filter((d) => d.connected).map((d) => ({ id: d.id, name: d.name, os: d.os })) : []),
    send: (paths, id) => { const u = fileDrop.unit && fileDrop.unit(id); (u || fileDrop).send(paths); }, });
  fileShelf.show({ view: o.view || 'recent', at: o.at });
}
// File Sharing › File Shelf › Shake to open (shared/shelf-watch.js): made only once it has been on.
let shelfWatcher = null;
function applyShelfWatch() {
  if (!helper || (!shelfWatcher && settings.files.shelf !== true)) return;
  shelfWatcher ||= require('../../shared/shelf-watch.js').shelfWatch({ helper: () => helper,
    on: () => settings.files.shelf === true && !modulesAtStart.includes('files'), open: (at) => showFileShelf({ view: 'shelf', at }) });
  shelfWatcher.apply();
}

function pushState() {
  if (pushQueued) return;
  pushQueued = true;
  setImmediate(() => {
    pushQueued = false;
    if (fileShelf) fileShelf.refresh(); // nothing while its window is closed
    applyShelfWatch(); // nothing while File Shelf's Shake to open is off
    try {
      if (android) android.refresh(); // the Android phones we serve to the mesh, when that changed
      const s = buildState();
      s.inviting = phoneInviteView(s);
      // Jump shortcuts at home (shared/jumpkeys.js): Electron's global shortcuts, X11 only (Wayland gives none).
      if (kvm && app.isReady()) {
        if (!jumpKeys) jumpKeys = new (require('../../shared/jumpkeys.js').GlobalJumps)(require('electron').globalShortcut, (id) => kvm.jumpTo(id));
        jumpKeys.sync(kvm.hub.bus.connectedIds().length > 0 ? settings.kvm.jumps : null);
        if (s.kvmState) s.kvmState.jumpErrors = jumpKeys.errors;
      }
      if (pcScreen) pcScreen.sendState(); // the viewer learns what we share
      if (sendTo) sendTo.sync(hub.peers().filter((x) => !P.isPhoneOs(x.os))); // one Send to entry per paired computer
      if (pairSync) pairSync.check(); // tell the other computer what changed here
      if (edges) edges.tick(); // the matrix: ours to every device when it changed
      if (meshView) meshView.tick(); // a laptop's battery, for the phones' list of the mesh
      if (mgr) mgr.tick(); // mesh managers: what this computer can do and granted, to every computer
      const phase = s.pairing ? s.pairing.phase : null;
      if (phase === 'code' && lastPairPhase !== 'code') showMain(); // a code to compare: to the front
      lastPairPhase = phase;
      if (mainWin && !mainWin.isDestroyed()) mainWin.webContents.send('state', s);
      updateTray(s);
    } catch (e) {
      console.error('[state] error', e && e.stack ? e.stack : e);
    }
  });
}

// Device names everywhere.
function fillNames(t) {
  if (!t || !String(t).includes('{')) return t || '';
  const name = peerName();
  const v = { me: (device && device.name) || 'this computer', name, Name: name.charAt(0).toUpperCase() + name.slice(1) };
  return String(t).replace(/\{(me|name|Name)\}/g, (m, k) => v[k]);
}
const fillAll = (o) => (typeof o === 'string' ? fillNames(o) : Array.isArray(o) ? o.map(fillAll)
  : o && typeof o === 'object' ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, fillAll(v)])) : o);

// File Sharing › TwinDesk Drive (docs/drive.md): one engine, synced with every connected computer.
// Nothing of it loads until it's on.
function loadDrive() {
  if (drive) return drive;
  const host = require('../../shared/drive-host.js');
  drive = host.createMesh({
    settings, save: saveSettings, me: device.id, meName: device.name, userData: app.getPath('userData'),
    trash: (p) => require('electron').shell.trashItem(p),
    mesh: host.hubAdapter(hub, () => hostServer),
    onChange: pushState,
  });
  return drive;
}

function peerName() {
  const p = peerView();
  return (p && p.name) || 'the other computer';
}

// The other computer: {os, name, id, role}, null when nothing is paired.
function peerView() {
  const s = link.snapshot();
  if (s.session) return { os: s.session.os, name: s.session.name, id: s.session.id, role: s.session.role === 'host' ? 'guest' : 'host' };
  if (s.paired) return { os: s.paired.os, name: s.paired.macName, id: s.paired.macId, role: 'host' };
  const g = s.guests.slice().sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0))[0];
  return g ? { os: g.os, name: g.name, id: g.id, role: 'guest' } : null;
}

// Setup items that aren't ready.
function missing() {
  const m = [];
  if (session.type !== 'x11' && session.type !== 'wayland') m.push('session');
  if (session.type === 'wayland' && !system.inputAccess().uinput) m.push('input');
  if (fw.ok === false && !fw.checking) m.push('firewall');
  const h = kvm.view().helper;
  if (session.type === 'x11' && h && h !== 'starting') m.push('helper');
  return m;
}

// Setup shows once: until everything is ready or it's skipped (no desktop session: always).
function setupShows(miss) {
  if (!settings.setup.done && !fw.checking && !miss.length) {
    settings.setup.done = true;
    saveSettings();
  }
  return miss.includes('session') || (!settings.setup.done && !fw.checking && miss.some((x) => !settings.setup.skipped.includes(x)));
}

// The selected device is a phone: its controls go with state.phone (as one to one).
function selectedIsPhone() {
  const p = peerView();
  return !!(p && P.isPhoneOs(p.os));
}
function meshPhoneCtl() {
  const v = devctl && selectedIsPhone() ? devctl.view : null;
  return v ? { ctl: v, qs: v.qs || null, top: v.top || [] } : { ctl: null, qs: null, top: [] };
}

// Audio › Play phone sound here (Bluetooth): this computer as the phone's Bluetooth speaker (../a2dp.js). A computer is one phone's
// speaker at a time: the first phone that connected here (PhoneSet's first stack).
function loadBtAudio() {
  if (btAudio || !phone || !settings.audio.phoneBt) return btAudio;
  const { BtAudio } = require('../../shared/btaudio.js');
  btAudio = new BtAudio({
    server: phone.first.link,
    backend: new (require('../a2dp').LinuxA2dp)(),
    cfg: () => settings.audio,
    save: saveSettings,
  });
  btAudio.on('change', pushState);
  btAudio.apply();
  return btAudio;
}

// Connection › Pair a phone with a QR code (shared/ui-qrpair.js): this computer's id, name, addresses
// and port, and a nonce that pairs with Allow only, as the USB cable does; a new one every 10 minutes.
let qrPair = null;
function qrPairView() {
  if (!qrPair || Date.now() > qrPair.until) qrPair = { nonce: crypto.randomBytes(8).toString('hex'), until: Date.now() + 10 * 60000 };
  const port = hostServer && hostServer.port;
  const addrs = ownAddresses().filter((a) => isIPv4(a)).slice(0, 4);
  if (!port || !addrs.length) return { url: '', why: !addrs.length ? 'No network' : 'Starting…' };
  const q = new URLSearchParams({ id: device.id, n: device.name, a: addrs.join(','), p: String(port), k: qrPair.nonce });
  return { url: 'twindesk://pair?' + q.toString(), until: qrPair.until };
}
const qrKnows = (nonce) => !!qrPair && typeof nonce === 'string' && nonce === qrPair.nonce && Date.now() < qrPair.until;
// Connection › Wireless debugging › Pair with a QR code (shared/adbqr.js), for the active phone: on while shown.
let adbQr = null;
let adbQrState = null; // {text} | {done: 'paired' | 'timeout' | 'failed: …'}
function adbQrDo(on) {
  if (adbQr) { adbQr.stop(); adbQr = null; }
  adbQrState = null;
  const br = phone && phone.bridge;
  if (on && br && br.adb.available) {
    adbQr = require('../../shared/adbqr.js').startAdbQr({
      adb: br.adb,
      onPaired: () => br.pairedNow(),
      onEnd: (why) => { adbQr = null; adbQrState = { done: why }; pushState(); },
    });
    adbQrState = { text: adbQr.text };
  }
  pushState();
  return adbQrState;
}

// General › Advanced › Engines in use (shared/engines.js): the selected device's session.
function enginesView() {
  const s = hub && hub.selected;
  if (!link || !s || !s.connected) return null;
  return require('../../shared/engines.js').snapshot({
    current: link.current, il: s.il, lane: s.lane(), fx: link.fx, fx2: hub.sessions.fxShared.fx2 ? hub.sessions.fxShared.fx2.fx2 : null, net: net ? net.view : null,
    lan: lanType(link.current && link.current.address), screen: null,
  });
}

function buildState() {
  const miss = missing();
  const snap = link.snapshot();
  return {
    device,
    ...snap,
    // The device in session (link.snapshot's `session`): `session` below is this desktop's (X11 or
    // Wayland) and replaces it, which hid every phone page (Calls, Messages, Photos, Phone Files).
    peerSession: snap.session || null,
    peer: peerView(),
    // Every paired device (connected or not), and the mesh's selection and live links.
    peers: hub.peers({ indirect: true }),
    // The phones whose screen comes through another computer of the mesh (the sidebar opens it): iPhones on a USB cable, Android phones connected there.
    iosScreens: [...(ios ? ios.screens().map((pid) => ({ id: pid, name: (hub.mesh.known().find((x) => x.id === pid) || {}).name || 'iPhone', os: 'ios' })) : []), ...(android ? android.screens() : [])],
    matrix: edges ? edges.view() : null, // the Multi-device tab's matrix (shared/mesh-edges.js)
    pads: padShare ? padShare.view() : null, // Camera & Controller › Controller (shared/pad-share.js)
    mgr: mgr ? mgr.view() : null, // Multi-device › Mesh managers and the Mesh manager page (shared/mesh-mgr.js)
    mesh: { selectedId: hub.selectedId, connectedIds: hub.bus.connectedIds(), autoJoin: settings.mesh.autoJoin === true, pcBle: false, shareLogs: settings.mesh.shareLogs !== false, collectLogs: settings.mesh.collectLogs !== false },
    debug: dbg ? dbg.view() : null, // Debug tab (shared/debug-start.js)
    localApi: localApi ? localApi.view() : null, // General › Local API
    found: discovery.list(),
    discovery: { ...discovery.status },
    addresses: ownAddresses(),
    stream: ((sv) => ({ ...sv.state, remote: sv.remote, watching: sv.sentAccept === true }))((viewers && viewers.of(hub.selectedId)) || screen), // the page's device's Monitor 2
    wake: wake.view(),
    macInput: screen.macInput,
    input: kvm.mode,
    kvmState: { ...kvm.view(), message: fillNames(kvm.message), partnerName: kvm.partner && hub.sessions.get(kvm.partner) ? hub.sessions.get(kvm.partner).displayName() : '' }, // who the pointer is with (the Overview's sentence)
    kvm: { ...settings.kvm },
    layout: layoutSync.state(), // the shared layout: { rev, by, cells (this device's view), grid, targets }
    keys: settings.keys,
    monitor: settings.monitor,
    clipboard: { ...settings.clipboard, ...clip.view, needsWlClipboard: wlClipboardMissing },
    web: web ? web.view() : { cfg: { ...settings.web }, devices: [] }, // TwinDesk Web
    ui: settings.ui,
    look: Look.view(settings.ui, null), // Linux has no system accent colour to read
    app: settings.app,
    proximityLockSupported: proximityLock?.supported === true,
    engines: enginesView(),
    version: app.getVersion(),
    about: about || (about = aboutInfo(app)), // About page: this app and this computer
    updates: updates ? updates.view : null,
    firewall: fw,
    session: { ...session, input: helper.backend || '', access: session.type === 'wayland' ? system.inputAccess() : null, inputNote, helperError: helper.error || '' },
    audio: { ...settings.audio, ...sound.view(), mic: mic ? mic.view() : null, own: ownSound ? ownSound.view() : null },
    pcScreen: pcScreen.view(),
    files: { ...settings.files, ...fileDrop.view(), recent: fileRecv ? fileRecv.recent : [], received: receivedDir(settings, app.getPath('downloads')), smb: smb.view(), incoming: fileRecv.view(), drag: kvm.dragRecv.view(), macDrags: kvm.peerDrags, clip: fileClip.view(), session: session.type },
    terminal: { ...settings.terminal, ...terminal.view(), installedKey: undefined, installedKeys: undefined, server: sshd.view() },
    termMesh: require('../../shared/term-mesh.js').termMeshView({ // the Terminal page's computers (shared/ui-term-mesh.js)
      selfId: device.id, selfName: device.name, consent, pairSync, names: termNames,
      devices: () => hub.peers({ indirect: true }).map((d) => ({ id: d.id, name: d.name, os: d.os, connected: !!d.connected })),
      unit: (id) => { const u = terminal.byId.get(id); return u ? { ready: u.status === 'ready', why: u.status } : null; },
    }),
    apps: link.peerOs === P.OS.MAC ? apps.view() : peerApps.view(), // a PC's or Linux computer's apps come through peerapps.js
    pcApps: pcApps.view(),
    macApps: settings.macApps,
    notifs: { ...settings.notifs, ...notifs.view() },
    phoneMedia: nowPlaying ? nowPlaying.view : null,
    btAudio: btAudio ? btAudio.view : null,
    adbQr: adbQrState, // wireless debugging's pairing QR code (shared/ui-adbqr.js)
    history: historyKeeper ? historyKeeper.view() : null,
    modules: require('../../shared/modules.js').view(settings.modules, modulesAtStart), // General › Modules
    iosSign: iosSign ? iosSign.view : null, // TwinDesk iPhone
    deck: deck ? deck.view() : null, // the Deck page: shown while a device has a Deck
    remote: (phoneRemote && phoneRemote.view) || REMOTE_OFF, // Remote tab: the active phone's
    rezume: { ...(rezume ? rezume.view : { ...settings.rezume, connected: false }), mesh: rzSolo ? rzSolo.blocked() : '', meshWith: rzSolo ? rzSolo.view() : null }, // ReZume tab; mesh: why not (pick a device), and the picker
    camera: camShare ? { ...camShare.state, on: !!settings.camera.on } : { on: false }, // on: the switch (off, it stays loaded but stopped)
    vcam: vcam ? vcam.view() : { checked: true, supported: true, on: false },
    chats: chats ? chats.view() : null, // Messages' WhatsApp, Instagram… conversations
    startup: autostart.get(),
    setup: { missing: miss, show: setupShows(miss) },
    phone: phone ? { ...phone.view, settings: settings.phone, ...meshPhoneCtl() } : null,
    peerCtl: devctl && !selectedIsPhone() ? devctl.view : null, // a computer's controls on Overview
    mount: { ...(phoneDrive ? phoneDrive.view : {}), on: settings.mount.on },
    drive: drive ? drive.view() : { on: false, folder: settings.drive.folder || path.join(os.homedir(), 'TwinDesk Drive'), custom: !!settings.drive.folder }, // File Sharing › TwinDesk Drive
    folders: folders ? folders.view() : null, // File Sharing › Shared folders, and the Share folder sheet
    drop: drop ? drop.state() : null, // Drop (shared/drop-host.js): the page asks for the room when rev changes
    // Calls, Messages and Photos: the settings alone until the hub is loaded (setupHub).
    hub: phoneHub ? phoneHub.view : { ...settings.hub, connected: false },
    net: { ...(net ? net.view : {}), ...hotspotView(), side: wifi ? wifi.side : null, location: false, ble: settings.net.ble, blePc: false, bleWifiOff: settings.net.bleWifiOff, bleOff, radio: bleHost ? bleHost.radio : bleGuest ? bleGuest.state : 'off', transport: link.current ? link.current.transport : '', lan: lanType(link.current && link.current.address), tailscale: settings.net.tailscale !== false, tailnet: require('../../shared/tailnet.js').mine(), bleInput: settings.net.bleInput === true, iface: settings.net.iface || '', ifaces: ifaceChoices() },
  };
}

// This computer's addresses: the one the other computer can reach first (Overview shows only that one).
function ownAddresses() {
  const peer = String(link.snapshot().link.address || '').replace(/^::ffff:/, '');
  return rankAddresses(interfaces(), { peer, prefer: settings.net.iface || '', def: defaultIface() }); // #350
}

function onKvmChange() {
  if (kvm.mode !== lastMode) {
    lastMode = kvm.mode;
    if (phoneRemote) phoneRemote.refresh(); // the phones' Remote is taken only with the mouse at home
    screen.refreshInput();
  }
  pushState();
}

// ---- firewall, open at login ----

async function checkFirewall() {
  fw = { ...fw, checking: true };
  pushState();
  fw = { ...(await system.checkFirewall(!!store.read('firewall.json', {}).fixed)), checking: false };
  pushState();
}

async function fixFirewall() {
  fw = { ...fw, checking: true };
  pushState();
  try {
    await system.fixFirewall(fw.tool);
    if (fw.tool === 'ufw') store.write('firewall.json', { fixed: true });
    fw = { ...(await system.checkFirewall(true)), checking: false };
  } catch (e) {
    fw = { ...fw, checking: false, message: 'Not fixed: ' + e.message };
  }
  pushState();
}

// Input access on Wayland (system.js, #144): the helper's own, never the user's.
async function fixInput() {
  try {
    await system.fixInput();
    inputNote = 'Done. Only the TwinDesk helper can read and control the mouse and keyboard.';
  } catch (e) {
    inputNote = 'Not fixed: ' + e.message;
  }
  helper.stop();
  helper.start(); // as its setgid copy now
  pushState();
}
async function leaveInputGroup() {
  try {
    await system.leaveInputGroup();
    inputNote = 'Done. Log out and back in once to finish.';
  } catch (e) {
    inputNote = 'Not changed: ' + e.message;
  }
  pushState();
}
async function removeInput() {
  try {
    await system.removeInput();
    inputNote = 'Removed. Log out and back in once to finish. Sharing the mouse and keyboard on Wayland needs Fix again.';
  } catch (e) {
    inputNote = 'Not removed: ' + e.message;
  }
  helper.stop();
  helper.start();
  pushState();
}
let inputNote = '';

function setStartup(on) {
  autostart.set(!!on);
  pushState();
}

function saveSettings() {
  storeSettings(store, settings);
}

function statusLine(s) {
  switch (s.link.state) {
    case 'connected': return t('Connected to {name}', { name: s.link.macName });
    case 'connecting': return t('Connecting…');
    case 'reconnecting': return s.link.busy || t('Reconnecting…');
    case 'stopped': return t('Disconnected');
    case 'identity_changed': return t('Pair again');
    default: return t('Not paired');
  }
}

// ---- windows and tray ----

function createMainWindow() {
  const b = settings.windows.main || {};
  mainWin = new BrowserWindow({
    width: b.width || 900,
    height: b.height || 680,
    x: b.x,
    y: b.y,
    minWidth: 720,
    minHeight: 480,
    title: 'TwinDesk',
    icon: path.join(__dirname, '..', 'assets', 'icon.png'),
    backgroundColor: nativeTheme.shouldUseDarkColors ? '#2b2b2e' : '#e9e9ee',
    show: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload-app.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true,
    },
  });
  mainWin.loadFile(path.join(__dirname, 'app.html'), { query: { language: i18n.locale, look: Look.style(settings.ui.style), off: modulesAtStart.join(',') } });
  const win = mainWin;
  let shown = false;
  const show = () => {
    if (shown || win.isDestroyed()) return;
    shown = true;
    if (!startHidden) win.show();
  };
  win.once('ready-to-show', show);
  // Match the ordinary window's fallback without revealing a start-to-tray launch.
  win.webContents.once('did-finish-load', show);
  for (const ev of ['show', 'hide', 'minimize', 'restore']) mainWin.on(ev, () => applyBle()); // Bluetooth looks only while it's open
  mainWin.on('show', () => lookForPhones());
  mainWin.on('close', (e) => {
    saveBounds();
    if (!quitting && tray) { // no tray on this desktop: closing quits, or nothing would bring it back
      e.preventDefault();
      mainWin.hide();
    }
  });
}

// A new language restarts TwinDesk: every window then loads English and that language only
// (shared/lang/pick.js), not every catalog. Settings are already saved (synchronously).
function changeLanguage() {
  app.relaunch({ args: process.argv.slice(1).filter((a) => a !== '--hidden') }); // the window shows
  app.quit();
}

function saveBounds() {
  if (!mainWin || mainWin.isDestroyed() || mainWin.isMinimized()) return;
  settings.windows.main = mainWin.getNormalBounds();
  saveSettings();
}

function goTab(tab) {
  showMain();
  if (mainWin && !mainWin.isDestroyed()) mainWin.webContents.send('go', tab);
}

function showMain() {
  if (!mainWin || mainWin.isDestroyed()) return;
  if (mainWin.isMinimized()) mainWin.restore();
  mainWin.show();
  mainWin.focus();
}

function showUpdateWindow() {
  showMain();
  if (mainWin && !mainWin.isDestroyed()) {
    mainWin.webContents.send('show-update');
  }
}

function createTray() {
  try {
    const img = nativeImage.createFromPath(path.join(__dirname, '..', 'assets', 'tray.png'));
    img.addRepresentation({ scaleFactor: 2, buffer: nativeImage.createFromPath(path.join(__dirname, '..', 'assets', '[email protected]')).toPNG() });
    tray = new Tray(img);
  } catch (e) {
    console.error('[tray]', e.message); // no tray on this desktop: start TwinDesk again to show the window
    return;
  }
  tray.setToolTip('TwinDesk');
  tray.on('click', showMain);
  updateTray(buildState());
}

// The tray menu, by kind (shared/traymenu.js) like the PC's. Rebuilt when what it shows
// changes (some Linux trays only take a new menu, not changes to the old one). A new menu redraws
// an open one (GNOME's top bar flickered, #100), so nothing that changes by itself is in it: the
// round trip (ms) is only in the tooltip, and that too is set only when it changes.
let trayKey = '';
let trayTip = '';
function updateTray(s) {
  if (!tray) return;
  const tip = 'TwinDesk: ' + statusLine(s);
  if (tip !== trayTip) { trayTip = tip; tray.setToolTip(tip); }
  const connected = s.link.state === 'connected';
  const name = connected && s.peer ? s.peer.name : '';
  const k = settings.kvm;
  const away = kvm.mode === 'driving' || kvm.mode === 'driven';
  const sharing = s.pcScreen.mode !== 'off';
  const watching = screen.sentAccept === true;
  const found = s.found.filter((d) => !s.peer || d.id !== s.peer.id);
  const host = s.paired && s.paired.macName;
  const again = !connected && host && (s.link.state === 'stopped' || !!s.link.busy);
  const key = JSON.stringify([name, again, away, pcApps ? pcApps.moved.size : 0, kvm.linked, kvm.paused, kvm.locked, kvm.mode, settings.keys.lockKeys, sharing, s.pcScreen.mode, watching, k.driveOther, k.beDriven, settings.clipboard.enabled,
    settings.audio.send, settings.app.hud, k.keyboard, settings.files.edgeDrag, settings.files.shortcuts, settings.files.copyKeys, found.map((d) => [d.id, d.name, d.os]), s.updates && s.updates.available && s.updates.latest]);
  if (key === trayKey) return;
  trayKey = key;
  const other = name || t('Other Computer');
  const set = (section, partial, after) => {
    if (!applySettings(settings, section, partial)) return;
    saveSettings();
    if (after) after();
    pushState();
  };
  const kind = (os) => (os === 'mac' ? 'Mac' : os === 'linux' ? 'Linux' : os === 'ios' ? 'iPhone' : os === 'android' ? t('Phone') : 'PC');
  tray.setContextMenu(Menu.buildFromTemplate(trayMenu.template({
    off: modulesAtStart, // General › Modules: menus of modules that are off aren't there
    t,
    connected,
    status: connected ? t('Connected to {name}', { name }) : t('Not connected'),
    home: away ? () => kvm.home() : null,
    windowsBack: pcApps && pcApps.moved.size ? { label: t(pcApps.moved.size === 1 ? 'Bring the Window Back from {name}' : 'Bring {count} Windows Back from {name}', { count: pcApps.moved.size, name: other }), click: () => pcApps.bringBack() } : null,
    shared: { checked: kvm.linked && !kvm.paused, set: (on) => kvm.setShared(on) },
    lock: connected ? { label: t('Lock Cursor on {name} ({keys})', { name: kvm.mode === 'driving' ? other : device.name, keys: CL.keysLabel(settings.keys.lockKeys, 'linux') }), checked: kvm.locked, set: (on) => kvm.setLocked(on) } : null,
    keyboard: { checked: k.keyboard, set: (on) => set('kvm', { keyboard: on }, () => kvm.applyConfig()) },
    drive: { label: t('Use Mouse and Keyboard on {name}', { name: other }), checked: k.driveOther, set: (on) => set('kvm', { driveOther: on }, () => kvm.applyConfig()) },
    driven: { label: t('Let {name} Control {me}', { name: other, me: device.name }), checked: k.beDriven, set: (on) => set('kvm', { beDriven: on }, () => kvm.applyConfig()) },
    popup: { checked: settings.app.hud, set: (on) => set('app', { hud: on }) },
    screen: [
      { label: t('Share Screen'), checked: sharing, set: (on) => pcScreen.setMode(on ? 'last' : 'off') }, // in the mode last picked here
      { label: t('Extend'), checked: pcScreen.mode === 'extend', set: (on) => (on ? pcScreen.extend() : pcScreen.setMode('off')) },
      { label: t('Mirror'), checked: pcScreen.mode === 'mirror', set: (on) => pcScreen.setMode(on ? 'mirror' : 'off') },
      { sep: true },
      // Opens/closes the screen window (opening starts the other computer's sharing).
      { label: t('Receive Screen'), checked: watching, set: (on) => (on ? screen.open(false) : screen.close()) },
    ],
    clipboard: { checked: settings.clipboard.enabled, set: (on) => set('clipboard', { enabled: on }, () => clip.applySettings()) },
    sound: { checked: settings.audio.send, set: (on) => set('audio', { send: on }, () => sound.apply()) },
    drag: { checked: settings.files.edgeDrag, set: (on) => set('files', { edgeDrag: on }, () => kvm.applyConfig()) },
    shortcuts: { label: t('Copy and Paste Files ({copy}, {paste})', { copy: CL.keysLabel(settings.files.copyKeys, 'linux'), paste: CL.keysLabel(settings.files.pasteKeys, 'linux') }), checked: settings.files.shortcuts, set: (on) => set('files', { shortcuts: on }, () => { kvm.applyConfig(); fileClip.apply(); }) },
    found: found.map((d) => ({ label: d.name + ' (' + kind(d.os) + ')', click: () => {
      if (P.isPhoneOs(d.os)) return connectPhoneDev(d);
      discovery.clearInvite(d.id);
      link.startPairing({ address: d.address, port: d.port, macName: d.name, id: d.id });
      showMain();
    } })),
    byAddress: () => goTab('connection'),
    lookAgain: () => discovery.probe(),
    update: s.updates && s.updates.available ? { label: t('Download TwinDesk {version}…', { version: s.updates.latest }), click: showUpdateWindow } : null,
    fileShelf: showFileShelf,
    open: showMain,
    log: () => require('../../shared/applog.js').open(),
    quit: () => app.quit(),
  })));
}

// Audio › Microphone: loaded the first time one of its switches is on (each change applies it).
// Camera: the selected computer's camera here and this one's there (shared/camshare.js, over the
// hub's facade: the selected device), a phone's through its own stack (phoneview.js openCamera),
// and the running one's picture to the tab and the virtual camera (shared/vcam.js, ../vcam.js).
const tellPhones = () => { if (phone) for (const u of phone.all || []) u.bridge._tellPhone(); }; // each phone's Camera page says so
function loadVcam() {
  if (vcam) return vcam;
  const { VirtualCam } = require('../../shared/vcam.js');
  vcam = new VirtualCam({ driver: require('../vcam'), cfg: () => settings.camera, save: saveSettings, onChange: pushState, onReady: tellPhones, ui: () => mainWin });
  if (phone) for (const u of phone.all || []) u.views.vcam = vcam;
  vcam.check();
  return vcam;
}

function loadCamera() {
  if (camShare || !settings.camera.on) return camShare;
  const { CamShare } = require('../../shared/camshare.js');
  loadVcam();
  // One CamShare per connected device (shared/cam-multi.js): this computer's camera goes to every computer it's
  // shared with that opens it, while the camera picked at the top of Camera (Receive) shows here.
  const { CamMulti } = require('../../shared/cam-multi.js');
  camShare = new CamMulti({
    hub,
    CamShare,
    getLanguage: () => i18n.locale,
    cfg: () => settings.camera,
    save: saveSettings,
    popup: (kind, text, presentation) => hud && hud.show(kind, presentation || text),
    onChange: pushState,
  });
  return camShare;
}

// Receive: whose camera shows here (Camera's picker at the top), whatever the sidebar selects.
function setCameraFrom(id) {
  if (camShare) return camShare.setFrom(id);
  settings.camera.from = typeof id === 'string' ? id.slice(0, 80) : '';
  saveSettings();
  pushState();
}

// Camera's switch: on loads it; off, whatever runs stops (every phone's camera too) and nothing is shared.
function setCamera(on) {
  settings.camera.on = !!on;
  saveSettings();
  if (on) loadCamera();
  else {
    if (camShare) {
      camShare.closeView();
      camShare.stopSending();
      camShare.sendPolicy();
    }
    if (phone) for (const u of phone.all || []) for (const v of u.views.list()) if (v.kind === 'camera') u.views.close(v.id);
  }
  tellPhones();
  pushState();
}

// ReZume (shared/rezume.js) between this computer and a phone, while that phone is the only device
// connected (shared/rezume-solo.js): between two computers it needs Multi-device off.
function loadReZume() {
  if (rezume || !settings.rezume.on) return rezume;
  try { return loadReZumeNow(); } catch (e) { console.error('[rezume] couldn’t start: ' + (e && e.stack || e)); rezume = null; return null; }
}
function loadReZumeNow() {
  const { shell } = require('electron');
  const { ReZume } = require('../../shared/rezume.js');
  const { ReZumeShelf } = require('../../shared/rezume-shelf.js');
  const { phoneAdb } = require('../../shared/rezume-solo.js');
  const act = require('../activity').create({ helper });
  const solo = () => (phone && rzSolo.id() ? phone.unit(rzSolo.id()) : null);
  const name = () => { const pr = rzSolo.link.peer(); return pr ? pr.name : 'the phone'; };
  // A document goes through Files, which is the selected device's: the device ReZume is with is
  // selected for it (as crossing to it with the pointer does).
  const toPartner = () => { const to = rzSolo.id(); return !!to && (hub.selectedId === to || !!hub.select(to)); };
  rezume = new ReZume({
    link: rzSolo.link,
    cfg: () => settings.rezume,
    detect: () => act.detect(),
    appIcon: (a) => act.appIcon(a),
    open: { url: (u) => shell.openExternal(u), file: (f) => shell.openPath(f), phoneApp: (pkg, n) => { const u = solo(); if (u) u.views.openApp(pkg, n || (u.phone.apps.find((a) => a.id === pkg) || {}).name); } },
    cacheDir: path.join(app.getPath('temp'), 'TwinDesk ReZume'),
    pick: (o, ways) => require('../../shared/rzpick.js').pick(o, ways, { peer: name(), language: i18n.locale }),
    adb: () => { const u = solo(); return phoneAdb(u && u.bridge); },
    phoneApps: () => { const u = solo(); return (u && u.phone.apps) || []; },
    sendFile: (p, batch) => toPartner() && !!fileDrop.sendBatch([p], 'rezume', batch),
    expectFile: (batch, dir) => { if (toPartner()) fileRecv.expectBatch(batch, dir || receivedDir(settings, app.getPath('downloads')), 0, false); },
    save: saveSettings,
  });
  rezume.on('change', pushState);
  rezume.on('opened', (o) => hud && hud.show('home', { key: o.how === 'sent' ? 'Sent to {name}: {title}' : 'From {name}: {title}', vars: { name: name(), title: o.title } }));
  rezumeShelf = new ReZumeShelf({ rezume, cfg: () => settings.rezume, peerName: name, appIcon: path.join(__dirname, '..', 'assets', 'icon.png') });
  rezume.apply();
  return rezume;
}

// Remote: made for every phone once it's turned on (or Keyboard's voice typing is).
const REMOTE_OFF = { allow: false, why: '', opened: false, using: false, pad: { on: false, supported: true, live: false, busy: '', message: '', name: '' } };
function loadRemote() {
  if (!phoneRemote || (!settings.remote.allow && !settings.kvm.keyboard)) return null;
  phoneRemote.load();
  return phoneRemote;
}

// The Deck (shared/deck.js): made once, then one per phone (deck.add) and per web device (deck.web).
// Not loaded at all while its module is off (General › Modules).
function loadDeck() {
  if (modulesAtStart.includes('deck')) return null;
  if (!deck) {
    const { clipboard: cb } = require('electron');
    deck = require('../../shared/deck.js').startDeck({
      platform: 'linux', helper: () => helper, server: null, settings: () => settings, saveSettings,
      readClipboard: () => cb.readText(), onChange: pushState,
    });
  }
  return deck;
}

function loadMic() {
  if (mic || !(settings.audio.micSend || settings.audio.micReceive)) return mic;
  const { Mic } = require('../../shared/mic.js');
  mic = new Mic({ link: hub.audioLink(), cfg: () => settings.audio, onChange: pushState, meshHub: hub });
  return mic;
}

app.on('before-quit', () => {
  if (fileShelf) fileShelf.shutdown();
  proximityLock?.shutdown();
  if (web) web.shutdown();
  batteryAlerts.reset();
  if (mic) mic.shutdown();
  quitting = true;
  theme.stop();
  saveBounds();
  if (discovery) discovery.stop();
  if (pcScreen) pcScreen.shutdown();
  if (pcApps) pcApps.shutdown();
  if (peerApps) peerApps.shutdown();
  desktopApps.shutdown();
  if (notifs) notifs.shutdown();
  if (phone) phone.shutdown();
  if (wired) wired.stop();
  if (devctl) devctl.stop();
  if (chats) chats.stop();
  if (phoneDrive) phoneDrive.shutdown();
  if (phone && phone.bridge) phone.bridge.adb.killServer();
  if (phoneHub && phoneHub.audio) phoneHub.audio.stop(); // the phone's calls go back to it
  if (phoneHub && phoneHub.share) phoneHub.share.stop();
  if (phoneHub && phoneHub.phoneNet) phoneHub.phoneNet.close(); // this computer's proxy as it was (shared/phonenet.js)
  if (callwin) callwin.close();
  if (kvm) kvm.shutdown(); // gives back any captured input and stops the helper
  loopback.shutdown();
});

// Closing the main window only hides it while there is a tray; the app lives there until Quit.
app.on('window-all-closed', () => { if (!tray) app.quit(); });