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.

51.1 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith, Erdoğan Yeşil. GPL-3.0, see LICENSE.
// Actions from the control window (and the menu bar): validate, save settings, apply.
'use strict';

const { ipcMain, shell, app, screen, dialog, clipboard, Menu } = require('electron');
const P = require('../../shared/protocol.js');
const CL = require('../../shared/cursorlock.js');
const Crossing = require('../../shared/crossing.js');
const { LINKS } = require('../../shared/about.js');
const store = require('./store');
const { planConnect, settleConnect, sessionIsUp } = require('../connect-plan');

const SETTINGS_URLS = {
  screen: 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture',
  accessibility: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility',
  inputMonitoring: 'x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent',
  localNetwork: 'x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork',
  fullDisk: 'x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles',
  bluetooth: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Bluetooth',
  location: 'x-apple.systempreferences:com.apple.preference.security?Privacy_LocationServices',
  extensions: 'x-apple.systempreferences:com.apple.ExtensionsPreferences?Sharing',
};
const TABS = ['phone', 'overview', 'connection', 'mirror', 'papps', 'calls', 'messages', 'media', 'pfiles', 'share', 'receive', 'cursor', 'keyboard', 'activity', 'clipboard', 'notifications', 'files', 'mount', 'terminal', 'audio', 'camera', 'remote', 'deck', 'rezume', 'apps', 'multi', 'debug', 'web', 'airplay', 'iossign', 'general', 'about'];

const bool = (v) => !!v;
const clamp = (lo, hi, dflt) => (v) => {
  const n = Number(v);
  return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : dflt;
};
const oneOf = (list, dflt) => (v) => (list.includes(v) ? v : dflt);
const devId = (v) => (typeof v === 'string' ? v.slice(0, 200) : ''); // an audio device's id (shared/mic.js)
// A global shortcut: at least Control, Option or Command, plus one key (Electron accelerator).
const KEY = /^(?:(?:Control|Alt|Shift|Command)\+){1,4}(?:[A-Z0-9]|F(?:[1-9]|1[0-9]|2[0-4])|Space|Tab|Backspace|Delete|Enter|Up|Down|Left|Right|[`\-=[\];',./\\])$/;
const accel = (dflt) => (v) => (typeof v === 'string' && KEY.test(v) && /Control|Alt|Command/.test(v) ? v : dflt);

// Allowed keys and their validators, per settings group.
const SCHEMA = {
  virtual: { enabled: bool, width: (v) => Math.round(clamp(640, 3840, 1920)(v)), height: (v) => Math.round(clamp(480, 2160, 1080)(v)), hiDPI: bool, hz: oneOf([30, 60], 60) },
  kvm: {
    pcSide: oneOf(P.SIDES, 'right'), mouse: bool, keyboard: bool, driveOther: bool, beDriven: bool,
    resistancePx: (v) => Math.round(clamp(0, 400, 120)(v)), crossingModifier: Crossing.modifier, stayFullscreen: bool, speed: clamp(0.25, 4, 1), scrollSpeed: clamp(0.25, 4, 1), reverseScroll: bool, hotkeySwitch: bool, linked: bool, gestures: bool, ble: bool, syncPads: bool, shakeHome: bool, portalsOn: bool, portalKeys: oneOf(['there', 'back', 'both'], 'there'),
    jumps: require('../../shared/jumpkeys.js').clean, // jump shortcuts (Mouse › Screen, Keyboard)
  },
  keys: { swapCtrlCmd: bool, hotkey: oneOf(P.HOTKEYS, 'AltRight'), lockKeys: (v) => CL.validKeys(v, CL.DEFAULT_KEYS.mac), emergencyKeys: Crossing.emergency, modMap: require('../../shared/modmap.js').clean },
  app: { openAtLogin: bool, keepAwake: bool, keepAwakeAlways: bool, hud: bool, inputProtocol: oneOf(['udp', 'tcp'], 'udp'), keepPinging: bool, localApi: bool, lockTogether: bool }, // localApi: General › Local API (Debug's MCP server too)
  mesh: { autoJoin: bool, shareLogs: bool, collectLogs: bool },
  updates: { auto: bool, skipped: (v) => (typeof v === 'string' ? v.slice(0, 40) : ''), install: bool },
  audio: { send: bool, receive: bool, muteLocal: bool, volume: clamp(0, 1, 1), phoneMedia: bool, micSend: bool, micReceive: bool, micDevice: devId, micOut: devId, routes: (v) => require('../../shared/sound-route.js').normRoutes(v), sync: bool }, // mic*: shared/mic.js; routes, sync: the mixer (shared/sound-route.js)
  terminal: { allowPc: bool, connectPc: bool },
  files: { shelf: bool, acceptDrops: bool, reveal: bool, dragEdge: bool, outboxHours: oneOf([0, 1, 24, 168], 24), clipReceived: bool, shortcuts: bool, copyKeys: accel('Control+Alt+C'), pasteKeys: accel('Control+Alt+V') },
  notifs: { send: bool, receive: bool, hideText: bool, batteryAlerts: bool },
  smb: { connectPc: bool, from: (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string').slice(0, 32) : 'all') }, // from: whose shared folders connect here (File Sharing, Multi-device)
  apps: { offer: bool, onVirtual: bool, moveWindows: bool, moveKey: oneOf(['ControlRight', 'ControlLeft', 'ShiftRight', 'ShiftLeft', 'AltRight', 'AltLeft', 'MetaRight', 'MetaLeft'], 'MetaRight') }, // moveWindows: Apps › Move windows (movewin.js)
  receive: { on: bool, fullScreen: bool, input: bool, framegen: bool },
  sharing: { remote: bool, pace: oneOf(['fast', 'smooth', 'steady'], 'fast'), fps: oneOf([0, 30, 60], 0) },
  papps: { on: bool },
  phone: { sound: bool, bitrateMbps: (v) => Math.round(clamp(2, 40, 8)(v)), maxSize: oneOf([0, 1920, 1600, 1280, 1024], 0), wallpaper: bool, input: oneOf(['adb', 'phone'], 'adb'), inputPicked: bool, mirror: oneOf(['auto', 'adb', 'native'], 'auto'), soundVia: oneOf(['auto', 'adb', 'native'], 'auto'), enterSends: bool, enterAll: bool, arrowSwipe: bool, hover: bool, uhid: bool, direct: bool, lowLatency: bool, keepPanelOff: bool },
  mount: { on: bool },
  clipboard: {
    enabled: bool, send: bool, receive: bool, mode: oneOf(['switch', 'instant'], 'instant'),
    skipConcealed: bool, maxKB: oneOf([16, 64, 256], 256), historySize: (v) => Math.round(clamp(0, 100, 20)(v)), images: bool, queue: bool, queueLatest: bool,
  },
};

function setupIpc(ctx) {
  const { settings, pushState } = ctx;
  const t = ctx.t || ((text) => text);

  function save() {
    store.saveSettings(settings);
    pushState();
  }

  function setGroup(group, partial) {
    const schema = SCHEMA[group];
    for (const [k, v] of Object.entries(partial || {})) if (schema[k]) settings[group][k] = schema[k](v);
    save();
  }

  // "Connect by address" / Pair on a found device: a computer that dials us is invited,
  // a computer this Mac dials (a Mac, Windows or Linux host) is dialled.
  const connect = ctx.state.connect;
  const report = (message, error = false, pending = null, messageKey = '', messageVars = {}) => {
    Object.assign(connect, { busy: false, message, error, pending, messageKey, messageVars });
    pushState();
  };
  const up = (id) => {
    const clients = ctx.server.server && ctx.server.server.clients ? [...ctx.server.server.clients.values()] : [];
    const authedHostIds = [];
    if (ctx.link && ctx.link.list) {
      for (const l of ctx.link.list()) if (l && l.authed && l.pairing) authedHostIds.push(l.pairing.macId);
    }
    return sessionIsUp(id, { current: ctx.server && ctx.server.current, clients, authedHostIds });
  };
  // The pending "Asked … / Connecting …" hint ends when that device's session is up (any device: it
  // needn't be the selected one).
  if (ctx.hub) ctx.hub.bus.onPeer('welcome', (deviceId) => {
    const next = settleConnect(connect, { deviceId });
    if (!next) return;
    Object.assign(connect, next);
    pushState();
  });
  async function connectTo(dev, address) {
    const { discovery, pairing } = ctx;
    const link = ctx.link; // the guest links (links.js): one per host
    const plan = planConnect({
      dev,
      address,
      pairedIds: pairing.list().map((p) => p.id),
      hosts: link.hosts || [],
    });
    // Already on this socket: leave the live session alone (the hint was stuck on "Asked …").
    if (plan.id && up(plan.id)) return report('');
    if (plan.action === 'phone') {
      report('');
      return ctx.phone.connect(plan.id);
    }
    if (plan.action === 'invite') {
      discovery.invite(plan.address);
      if (plan.inviting) { // the popup says Pair has to be pressed on the phone, for a minute at most
        const inv = { id: plan.id, name: plan.name };
        connect.inviting = inv;
        setTimeout(() => { if (connect.inviting === inv) { connect.inviting = null; pushState(); } }, 60 * 1000);
      }
      return report(plan.message, false, plan.pending, plan.messageKey, plan.messageVars);
    }
    if (plan.action === 'dial') {
      const l = link.get(plan.id);
      if (l) {
        if (plan.address && l.pairing && l.pairing.address !== plan.address) {
          l.pairing.address = plan.address;
          if (plan.port) l.pairing.port = plan.port;
          if (l.store) l.store.save(l.pairing);
        }
        // A host we dial: if it is also connected to us (it dials us), that socket goes first, then we dial.
        const inbound = ctx.server.server.clients.get(plan.id);
        if (inbound) {
          ctx.server.server.release(inbound);
          setTimeout(() => l.connect(true), 800);
        } else l.connect(true);
        return report(plan.message, false, plan.pending, plan.messageKey, plan.messageVars);
      }
    }
    report('');
    link.startPairing({ address: plan.address, port: plan.port || P.PORT, macName: plan.name });
  }

  const actions = {
    async connectAddress(text) {
      const address = String(text || '').trim();
      if (!/^(\d{1,3})(\.\d{1,3}){3}$/.test(address)) return report('Type an address like 192.168.1.20.', true);
      if (ctx.state.addresses.includes(address)) return report('That’s this Mac.', true);
      Object.assign(connect, { busy: true, message: `Looking at ${address}…`, error: false, messageKey: 'Looking at {address}…', messageVars: { address } });
      pushState();
      const dev = await ctx.discovery.ask(address);
      connectTo(dev, address); // no answer: try the WSS port directly (a Mac host answers there)
    },
    connectPhone(deviceId) {
      ctx.proximityLock?.cancel();
      ctx.phone.connect(String(deviceId));
    },
    disconnectPhone() {
      ctx.proximityLock?.cancel();
      ctx.phone.disconnect();
    },
    // Disconnect the session (phone or computer); Connect again / Take over the Mac we're a guest of.
    disconnect() {
      ctx.proximityLock?.cancel();
      if (ctx.server.current && P.isPhoneOs(ctx.server.current.os)) return ctx.phone.disconnect();
      ctx.server.disconnect();
    },
    connectAgain() {
      // Connect again, or Take over, the selected computer (its link)
      const l = ctx.hub.selectedId ? ctx.link.get(ctx.hub.selectedId) : null;
      if (l) l.connect(true);
    },
    setPhone(partial) {
      setGroup('phone', partial);
      if (partial && 'input' in partial) ctx.phone.bridge.tellVia();
      if (partial && ('input' in partial || 'mirror' in partial || 'soundVia' in partial)) for (const u of ctx.phone.all || []) u.bridge.modesChanged(); // ADB or Native (shared/phonemodes.js), every phone
      if (partial && ('enterSends' in partial || 'arrowSwipe' in partial) && ctx.phoneViews) ctx.phoneViews.applyOpts(); // the open phone windows light their buttons
      if (partial && 'keepPanelOff' in partial) {
        const units = ctx.phone && ctx.phone.all;
        if (units) {
          for (const u of units) u.views?.panelPreferenceChanged();
        } else ctx.phoneViews?.panelPreferenceChanged();
      }
    },
    phonePair(arg) {
      if (arg && typeof arg === 'object') ctx.phone.bridge.pair(arg.code, arg.where);
    },
    // open: true | false, or {open, id}: that phone's screen (#263), else the active phone's.
    phoneScreen(arg) {
      const { open, id } = arg && typeof arg === 'object' ? arg : { open: arg };
      const u = id && ctx.phone.unit ? ctx.phone.unit(String(id)) : null;
      const views = u ? u.views : ctx.phoneViews;
      if (open === false) {
        for (const v of views.list()) if (v.kind === 'screen') views.close(v.id);
      } else views.openScreen();
    },
    // The phone the Phone pages show (Mirroring's phone picker, #263).
    phonePick(id) {
      if (typeof id === 'string' && ctx.phone.pick) ctx.phone.pick(id);
    },
    phoneCamera(m) {
      const { open, opts } = m && typeof m === 'object' ? m : { open: m }; // preload-control: {open, opts}
      if (open === false) {
        for (const v of ctx.phoneViews.list()) if (v.kind === 'camera') ctx.phoneViews.close(v.id);
      } else ctx.phoneViews.openCamera(opts);
    },
    takePhoto() { // Camera › Take a photo with the phone (shared/phonephoto.js), the active Android phone
      return !!ctx.takePhoto && ctx.takePhoto();
    },
    scanDocument() { // Camera › Scan document (shared/phonephoto.js), the active Android phone
      return !!ctx.scanDocument && ctx.scanDocument();
    },
    phoneOpenApp(arg) {
      if (arg && typeof arg.id === 'string') ctx.phoneViews.openApp(arg.id.slice(0, 200), String(arg.name || '').slice(0, 100));
    },
    phoneCloseView(id) {
      ctx.phoneViews.close(Number(id));
    },
    phoneScreenAct(key) {
      if (key === 'rotate' || key === 'screenPower') ctx.phoneViews.screenAct(key);
    },
    // Right-click on a phone app: open it, or keep it in the Dock (phoneview.js).
    phoneAppMenu(arg) {
      if (!arg || typeof arg.id !== 'string' || !/^[\w.]{1,200}$/.test(arg.id)) return;
      const name = String(arg.name || arg.id).slice(0, 100);
      Menu.buildFromTemplate([
        { label: t('Open in a Window'), click: () => ctx.phoneViews.openApp(arg.id, name) },
        { label: t('Add to Dock'), click: () => ctx.phoneViews.pin(arg.id, name) },
      ]).popup();
    },
    phoneInstallFull() {
      ctx.phone.bridge.installFull();
    },
    // Phone › Apps › Install Apps: .apk files picked here, installed over ADB (shared/apkinstall.js).
    phoneInstallApps() {
      if (ctx.phone) return require('../../shared/apkinstall.js').choose(ctx.phone.bridge, t);
    },
    phoneRetry() {
      ctx.phone.bridge.retry(); // also Set Up, when nothing used wireless debugging
    },
    // The phone in Finder (phonedrive.js).
    phoneMount() {
      if (settings.mount.on) ctx.phoneDrive.mount();
    },
    // The Mount page's switch: off unmounts and stops everything (nothing runs until Mount anyway).
    setMount(partial) {
      setGroup('mount', partial);
      if (!settings.mount.on) ctx.phoneDrive.stop();
    },
    phoneUnmount() {
      ctx.phoneDrive.unmount();
    },
    pairWith(deviceId) {
      const dev = ctx.discovery.get(String(deviceId));
      if (dev) connectTo(dev);
    },
    // Devices list: Use makes the device the one the features talk to; Forget removes its pairing.
    selectPeer(deviceId) {
      if (ctx.hub) ctx.hub.select(String(deviceId));
    },
    // An iPhone's screen through a USB cable of the mesh (shared/ios-mesh.js), wherever its app is connected.
    iosScreen(deviceId) {
      if (ctx.iosScreen) ctx.iosScreen(String(deviceId).slice(0, 64));
    },
    forgetPeer(deviceId) {
      if (!ctx.hub) return;
      ctx.proximityLock?.forget(String(deviceId));
      ctx.hub.forgetPeer(String(deviceId));
      ctx.kvm.forgetDevice(String(deviceId)); // it leaves the shared layout too (docs/mesh.md)
      ctx.terminal.forget(String(deviceId));
      if (ctx.batteryAlerts) ctx.batteryAlerts.forget(String(deviceId));
    },
    confirmGuestCode() {
      ctx.link.confirmCode();
    },
    cancelGuestPair() {
      connect.inviting = null;
      pushState();
      ctx.link.cancelPair();
    },
    forgetHost(hostId) {
      ctx.link.forget(String(hostId));
    },
    refreshDiscovery() {
      ctx.discovery.refresh();
    },
    copyText(text) {
      if (typeof text === 'string' && text.length < 200) clipboard.writeText(text);
    },
    // Activity copies a notification or a call. Text only, capped, never a path and never a shell.
    copyLiteral(text) {
      if (typeof text !== 'string' || !text || text.length > 256 * 1024 || !clipboard) return;
      clipboard.writeText(text);
    },
    // Ask first (that puts TwinDesk in the System Settings list), then open the pane.
    async allowPermission(kind) {
      if (!SETTINGS_URLS[kind]) return;
      let granted = false;
      if (kind !== 'localNetwork' && ctx.helper.running) {
        try {
          granted = !!(await ctx.helper.request('requestAccess', { kind })).granted;
        } catch {}
      }
      if (!granted) shell.openExternal(SETTINGS_URLS[kind]);
      ctx.refreshPermissions();
    },
    skipSetup(missing) {
      settings.ui.setupSkipped = String(missing || '').slice(0, 200);
      settings.ui.setupDone = true;
      save();
    },
    // by: 'apps' when Mac apps on the PC turned it on/off by themselves; a person's switch ends that.
    setSharing(on, by) {
      if (by !== 'apps' && ctx.apps) ctx.apps.autoShare = false;
      settings.sharing.on = !!on;
      save();
      // Through Bluetooth the picture needs Wi-Fi first (netlink.js); it starts once the session is on it.
      if (on) ctx.net.need('share').then(() => settings.sharing.on && ctx.displays.applyVirtual().then(() => ctx.stream.restart('sharing on')));
      else {
        ctx.net.release('share');
        ctx.stream.stop('off');
        ctx.input.releaseAll();
        ctx.displays.applyVirtual(); // removes the virtual display
      }
    },
    // Who may start our sharing, and smoothness vs. sharpness.
    setSharingOpts(partial) {
      const was = { steady: settings.sharing.pace === 'steady', fps: settings.sharing.fps || 0 };
      setGroup('sharing', partial);
      ctx.pcView.applySettings(); // playback pace in the open viewer
      // Steady is set up per session (the viewer's answer), the frame rate too: a new one.
      if (ctx.stream && ctx.stream.active && (was.steady !== (settings.sharing.pace === 'steady') || was.fps !== (settings.sharing.fps || 0))) ctx.stream.restart('playback changed');
    },
    // Start/stop the other computer's sharing or switch its Extend/Mirror from here.
    remoteScreen(arg) {
      ctx.pcView.control(arg || {});
    },
    wakePeer(id) {
      ctx.wake.wake(String(id));
      setTimeout(() => ctx.link.poke(), 8000); // a Mac host: try again once it had time to wake
    },
    setWakeOnLan(on) {
      ctx.wake.setWomp(!!on);
    },
    setStreamInput(on) {
      settings.streamInput = !!on;
      save();
      if (!on) ctx.input.releaseAll();
      for (const pid of ctx.hub.bus.connectedIds()) ctx.hub.bus.send(pid, { t: P.T.STREAM_INPUT, on: !!on }); // every viewer goes view-only when off
    },
    // Share this Mac's screen with one device its own way: { mode: 'default'|'none'|'mirror'|'virtual', displayId? }.
    setStreamTarget(o, more) {
      const { id, choice } = o && typeof o === 'object' ? o : { id: o, choice: more };
      if (typeof id !== 'string' || !choice || typeof choice !== 'object') return undefined;
      const r = ctx.stream.setTarget(id, { mode: String(choice.mode), displayId: choice.displayId, place: typeof choice.place === 'string' ? choice.place : '', ...(choice.add === true ? { add: true } : {}), ...(Number.isInteger(choice.ch) ? { ch: choice.ch } : {}) });
      if (ctx.sendScreenState) ctx.sendScreenState(); // place goes in screen.state
      return r;
    },
    // null = the TwinDesk virtual display
    selectDisplay(displayId) {
      settings.sharing.displayId = displayId == null ? null : Number(displayId);
      save();
      if (typeof ctx.stream.noteViewIdentity === 'function') ctx.stream.noteViewIdentity();
      ctx.stream.restart('display selected');
    },
    // Extend: Monitor 2 is the TwinDesk virtual display. Mirror: it shows this Mac's main screen.
    setDisplayMode(mode) {
      if (mode === 'mirror') {
        const primary = ctx.displays.list().find((d) => d.primary && !d.virtual);
        if (primary) settings.sharing.displayId = primary.id;
        settings.virtual.enabled = false;
      } else {
        settings.sharing.displayId = null;
        settings.virtual.enabled = true;
      }
      save();
      if (typeof ctx.stream.noteViewIdentity === 'function') ctx.stream.noteViewIdentity();
      ctx.displays.applyVirtual().then(() => ctx.stream.restart(`mode ${mode}`));
    },
    setVirtual(partial) {
      setGroup('virtual', partial);
      ctx.displays.applyVirtual();
    },
    // Share screen › Add virtual display ({width, height}): one more screen to share to a device, there
    // while this Mac's screen is shared (displays.js). Slots 1…MAX_EXTRA; the name follows the slot.
    addVirtual(o) {
      const { MAX_EXTRA } = require('../displays.js');
      const list = Array.isArray(settings.virtuals) ? settings.virtuals.filter((v) => v && Number.isInteger(v.slot)) : [];
      let slot = 1;
      while (list.some((v) => v.slot === slot)) slot++;
      if (slot > MAX_EXTRA) return;
      const width = Math.round(clamp(640, 3840, 1920)(o && o.width));
      const height = Math.round(clamp(480, 2160, 1080)(o && o.height));
      settings.virtuals = [...list, { slot, name: `TwinDesk ${slot + 1}`, width, height, hiDPI: false }];
      save();
      ctx.displays.applyVirtual();
    },
    // An added virtual display's size (Share screen › Virtual displays): made again at the new size.
    resizeVirtual(o) {
      const slot = o && o.slot;
      const list = Array.isArray(settings.virtuals) ? settings.virtuals : [];
      const v = list.find((x) => x && x.slot === slot);
      if (!v) return;
      const width = Math.round(clamp(640, 3840, v.width)(o && o.width));
      const height = Math.round(clamp(480, 2160, v.height)(o && o.height));
      if (width === v.width && height === v.height && !!(o && o.hiDPI) === !!v.hiDPI) return;
      settings.virtuals = list.map((x) => (x === v ? { ...v, width, height, hiDPI: !!(o && o.hiDPI) } : x));
      save();
      ctx.displays.applyVirtual();
    },
    // Remove an added virtual display: the devices it was shared to get nothing (not another screen).
    removeVirtual(slot) {
      const list = Array.isArray(settings.virtuals) ? settings.virtuals : [];
      if (!list.some((v) => v && v.slot === slot)) return;
      const live = (ctx.displays.extras.get(slot) || {}).id;
      settings.virtuals = list.filter((v) => v && v.slot !== slot);
      save();
      if (live != null && ctx.stream.byId) {
        for (const [id, st] of ctx.stream.byId) if (st.choice && st.choice.mode === 'mirror' && Number(st.choice.displayId) === live) ctx.stream.setTarget(id, { mode: 'none' });
      }
      ctx.displays.applyVirtual();
    },
    setStreamMaxHeight(h) {
      settings.streamMaxHeight = [0, 1080, 1440, 2160].includes(Number(h)) ? Number(h) : 1080;
      save();
      ctx.stream.restart('stream size changed');
    },
    setBitrate(mbps) {
      settings.bitrateMbps = clamp(2, 100, 20)(mbps);
      save();
      ctx.stream.restart('bitrate changed');
    },
    // Cursor portals towards computer `peer`: {rules, peer} (mesh/kvm.js checks them against both sides' displays).
    setPortals(arg) {
      if (!arg || !ctx.kvm.setPortals(arg.rules, arg.peer)) return;
      save();
      ctx.kvm.config();
    },
    setKvm(partial) {
      const prev = { ...settings.kvm };
      setGroup('kvm', partial);
      ctx.kvm.settingsChanged(prev);
      if (partial && typeof partial.shared === 'boolean') ctx.kvm.setShared(partial.shared); // the Cursor tab's switch (Over Bluetooth through it)
      if (partial && typeof partial.locked === 'boolean') ctx.kvm.setLocked(partial.locked); // cursor lock: not a setting
      if (partial && 'keyboard' in partial) (ctx.remote() ? ctx.remote().refresh() : ctx.loadRemote()); // voice typing follows Keyboard
    },
    // The shared layout (docs/mesh.md): a device goes to a cell (a device there moves to its old cell, or
    // they swap); a device goes off the map. Invalid arguments are ignored; the new layout comes with the state.
    setLayoutCell(arg) {
      const { id, x, y } = arg || {};
      if (typeof id !== 'string' || !id || id.length > 64 || !Number.isInteger(x) || !Number.isInteger(y)) return;
      ctx.layoutSync.place(id, x, y);
    },
    // The monitor map (#225): a device dropped with its top-left at (x, y) in the plane; it goes where it may.
    moveOnMap(arg) {
      const { id, x, y, snap } = arg || {};
      if (typeof id !== 'string' || !id || id.length > 64 || !Number.isFinite(x) || !Number.isFinite(y)) return;
      ctx.layoutSync.move(id, x, y, Number.isFinite(snap) ? Math.max(0, Math.min(2000, snap)) : undefined);
    },
    resetMap() {
      ctx.layoutSync.resetWorld();
    },
    setMapSkip(on) { // offline computers: passed or not
      ctx.layoutSync.setSkip(on === true);
    },
    setMapWhole(id, on) { // #376: device id takes the whole edge of a monitor it alone touches
      if (typeof id !== 'string' || !id || id.length > 64) return;
      ctx.layoutSync.setWhole(id, on === true);
    },
    removeFromLayout(id) {
      if (typeof id !== 'string' || !id || id.length > 64) return;
      ctx.layoutSync.remove(id);
    },
    setTerminal(partial) {
      const prev = settings.terminal.connectPc;
      setGroup('terminal', partial);
      ctx.terminal.applySettings();
      if (settings.terminal.connectPc !== prev) ctx.sshClient.applySettings();
    },
    openPcShell() {
      ctx.sshClient.openShell();
    },
    openSharingSettings() {
      shell.openExternal('x-apple.systempreferences:com.apple.Sharing-Settings.extension');
    },
    // File Sharing › TwinDesk Drive (shared/drive-host.js createMesh): loaded when turned on, and only then.
    setDrive(on) {
      const d = on ? ctx.loadDrive() : ctx.getDrive();
      if (d) d.setOn(!!on).then(pushState, pushState);
      else { settings.drive.on = false; save(); }
    },
    async pickDriveFolder() {
      const r = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'], buttonLabel: t('Use This Folder') });
      if (r.canceled || !r.filePaths[0]) return;
      actions.setDriveFolder(r.filePaths[0]);
    },
    resetDriveFolder() {
      actions.setDriveFolder('');
    },
    setDriveFolder(f) {
      const d = ctx.getDrive();
      if (d) d.setFolder(f).then(pushState, pushState);
      else { settings.drive.folder = f; save(); }
    },
    openDriveFolder() {
      const d = ctx.getDrive();
      if (d) shell.openPath(d.folder());
    },
    setFiles(partial) {
      setGroup('files', partial);
      if (partial && ('shortcuts' in partial || 'copyKeys' in partial || 'pasteKeys' in partial)) ctx.fileClip.apply();
      ctx.fileSend.sendPolicy();
      ctx.kvm.config();
    },
    // Send files (paths from the drop zone or the Choose… dialog).
    sendFiles(paths, to) {
      if (paths && !Array.isArray(paths) && typeof paths === 'object') ({ paths, to } = paths); // {paths, to}: one message (preload)
      const list = (Array.isArray(paths) ? paths : []).filter((p) => typeof p === 'string' && p.startsWith('/')).slice(0, 1000);
      if (!list.length) return;
      // Multi-device: the devices picked on File Sharing (each its own send, now or when it's back), else the selected one.
      const ids = Array.isArray(to) ? to.filter((x) => typeof x === 'string').slice(0, 10) : [];
      const units = ids.map((id) => ctx.fileSend.unit && ctx.fileSend.unit(id)).filter(Boolean);
      if (units.length) for (const u of units) u.send(list);
      else ctx.fileSend.send(list); // now, or when the device is back (shared/outbox.js)
    },
    pauseSend(batch) { if (typeof batch === 'string') ctx.fileSend.pause(batch); },
    resumeSend(id) { if (typeof id === 'string') ctx.fileSend.resume(id); },
    forgetSend(id) { if (typeof id === 'string') ctx.fileSend.forget(id); },
    async chooseSendFiles(to) {
      const r = await dialog.showOpenDialog({ properties: ['openFile', 'openDirectory', 'multiSelections'], buttonLabel: t('Send') });
      if (!r.canceled) actions.sendFiles(r.filePaths, to);
    },
    setNotifs(partial) {
      setGroup('notifs', partial);
      Object.assign(settings.notifs, require('../../shared/notifrules.js').clean(partial, settings.notifs)); // style, otpCopy, quiet, phoneApps
      save();
      ctx.notifs.applySettings();
      if (ctx.batteryAlerts) ctx.batteryAlerts.setting(!!settings.notifs.batteryAlerts);
    },
    muteNotifApp(arg) {
      if (arg && typeof arg.app === 'string') ctx.notifs.setMuted(arg.app.slice(0, 200), !!arg.muted);
    },
    // Full Disk Access has no request API: open the pane and show TwinDesk in Finder to drag in.
    allowFullDisk() {
      shell.openExternal(SETTINGS_URLS.fullDisk);
      const bundle = process.execPath.replace(/\/Contents\/MacOS\/[^/]+$/, '');
      if (bundle.endsWith('.app')) shell.showItemInFolder(bundle);
    },
    async pickDropFolder() {
      const r = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'], buttonLabel: t('Use This Folder') });
      if (r.canceled || !r.filePaths[0]) return;
      settings.files.folder = r.filePaths[0];
      save();
    },
    resetDropFolder() {
      settings.files.folder = '';
      save();
    },
    revealDrop(index) {
      ctx.drop.reveal(Number(index));
    },
    clearFiles() {
      ctx.drop.clearRecent();
      if (ctx.fileSend) ctx.fileSend.clearRecent();
    },
    showFileShelf(view) {
      ctx.showFileShelf({ view: view === 'shelf' ? 'shelf' : 'recent' });
    },
    setSmb(partial) {
      setGroup('smb', partial);
      if (settings.smb.connectPc) { ctx.smb.mountPc(); if (ctx.smb.applyFrom) ctx.smb.applyFrom(); }
      else ctx.smb.unmountPc();
    },
    // One switch: on = share the chosen folder (default ~/TwinDesk); off = stop sharing.
    setShareMac(on) {
      if (on) ctx.smb.startSharing();
      else ctx.smb.stopSharing();
    },
    async chooseShareFolder() {
      const r = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'], buttonLabel: t('Share This Folder') });
      if (r.canceled || !r.filePaths[0]) return;
      if (settings.smb.sharing) await ctx.smb.stopSharing();
      settings.smb.folder = r.filePaths[0];
      save();
      ctx.smb.startSharing(r.filePaths[0]);
    },
    stopSharingFolder() {
      ctx.smb.stopSharing();
    },
    openPcShare() {
      ctx.smb.openPc();
    },
    openDrive(id) { // another device's folder, connected here (Files)
      if (typeof id === 'string' && ctx.smb.openDevice) ctx.smb.openDevice(id);
    },
    setApps(partial) {
      setGroup('apps', partial);
      ctx.apps.applySettings();
      ctx.appSend.applySettings();
      if (ctx.pcApps) ctx.pcApps.applySettings(); // Move windows: it takes moved windows too
    },
    setReceive(partial) {
      setGroup('receive', partial);
      ctx.pcView.applySettings();
    },
    setPcApps(partial) {
      setGroup('papps', partial);
      ctx.pcApps.applySettings();
    },
    listPcApps() {
      ctx.pcApps.list();
    },
    openPcApp(id) {
      ctx.pcApps.open(String(id)); // Wi-Fi first through Bluetooth (main.js)
    },
    keepPcAppInDock(id) {
      ctx.pcApps.keepInDock(String(id));
    },
    showPcView() {
      ctx.net.need('view').then(() => ctx.pcView.show());
    },
    closePcView() {
      ctx.pcView.close();
      ctx.net.release('view');
    },
    // Bluetooth when not on one network (netlink.js, blepipe.js).
    setNet(partial) {
      if (partial?.ble === false && settings.net.ble !== false) ctx.proximityLock?.reset();
      if (typeof partial.ble === 'boolean') settings.net.ble = partial.ble;
      if (typeof partial.blePc === 'boolean') settings.net.blePc = partial.blePc;
      if (typeof partial.bleWifiOff === 'boolean') settings.net.bleWifiOff = partial.bleWifiOff; // blepolicy.js wifiQuiet
      if (typeof partial.tailscale === 'boolean') settings.net.tailscale = partial.tailscale; // shared/tailnet.js
      if (typeof partial.bleInput === 'boolean') settings.net.bleInput = partial.bleInput; // shared/bleinput.js
      save();
      ctx.ble.apply();
      if (partial.blePc === false && ctx.bleLook) ctx.bleLook.look(false); // computers off: stop looking now, not at the next tick
      pushState();
    },
    // The banner: the phone's hotspot is on; join it (remembered for that phone).
    netJoinHotspot(arg) {
      const c = ctx.server.current;
      const ssid = String((arg && arg.ssid) || '').trim().slice(0, 32);
      let pass = String((arg && arg.pass) || '').slice(0, 63);
      const saved = c && settings.net.hotspots[c.deviceId];
      if (!pass && saved && saved.ssid === ssid) pass = ctx.netSecret.open(saved.pass);
      if (!ssid || !c) return;
      settings.net.hotspots[c.deviceId] = { ssid, pass: pass ? ctx.netSecret.seal(pass) : '' };
      save();
      ctx.net.joinHotspot(ssid, pass);
    },
    netCancel() {
      ctx.net.cancel();
    },
    // Connect with Wi-Fi Direct (a session on Bluetooth), or with the phone's hotspot (on =
    // 'hotspot'), or back to Bluetooth: the link ends whatever it was made for (the screen too:
    // Bluetooth can't carry it).
    netWifi(on) {
      if (on) return void ctx.net.need(on === 'hotspot' ? 'hotspot' : 'user');
      ctx.net.drop();
      if (settings.sharing.on) actions.setSharing(false);
    },
    setAudio(partial) {
      setGroup('audio', partial);
      ctx.audio.applySettings();
      const mic = ctx.loadMic && ctx.loadMic(); // Microphone: loaded when first on
      if (mic) mic.apply();
      if (partial && ('micReceive' in partial || 'micOut' in partial) && ctx.phone && ctx.phone.bridge && ctx.phone.bridge._sound) ctx.phone.bridge._sound(); // a phone's microphone, now
      // Media controls: made for every phone when turned on; off, each one stops.
      const np = partial && 'phoneMedia' in partial && ctx.loadNowPlaying ? ctx.loadNowPlaying() : null;
      if (np) np.apply();
    },
    // The active phone's media controls on the Overview (shared/nowplaying.js, one per phone).
    phoneMedia(m) {
      const np = ctx.loadNowPlaying ? ctx.loadNowPlaying() : null;
      if (m && np) np.control(String(m.a || ''), m.pos);
    },
    phoneBtPick() {}, // no Bluetooth speaker mode on macOS
    // General › Modules (shared/modules.js): applies after a restart.
    setModules(m) {
      if (!m || typeof m !== 'object') return;
      const Mods = require('../../shared/modules.js');
      settings.modules = typeof m.restored === 'string' ? Mods.restored(settings.modules, m.restored) : Mods.set(settings.modules, String(m.id), m.on === true, m.wasOn === true);
      save();
      ctx.pushState();
    },
    // TwinDesk iPhone (shared/iossign.js): one action, and Choose an IPA….
    iosSign(o) {
      require('../../shared/iossign-host.js').act(ctx.iosSign, dialog, o);
    },
    iosSignIpa() {
      require('../../shared/iossign-host.js').pickIpa(ctx.iosSign, dialog);
    },
    // The Deck page (shared/ui-deck.js): the layout, and Try (runs a button here).
    deckSave(layout) {
      if (ctx.deck && layout && typeof layout === 'object') ctx.deck.save(layout);
    },
    deckTry(action) {
      if (ctx.deck && action && typeof action === 'object') ctx.deck.exec(action).catch(() => {});
    },
    // Remote tab: each phone's Remote page here (shared/perphone.js phoneRemote).
    setRemote(m) {
      if (!m || typeof m !== 'object') return;
      // Off at start: not made; turned on, made for every phone (and they hear it).
      if ('allow' in m && !ctx.remote() && m.allow === true) { settings.remote.allow = true; ctx.loadRemote(); }
      if ('allow' in m && ctx.remote()) ctx.remote().setAllow(m.allow === true);
      save();
      ctx.pushState();
    },
    // Camera tab: the selected computer's camera here, this Mac's there (shared/camshare.js). macOS
    // asks for the camera when sharing is first turned on.
    camera(m) {
      if (m && m.do === 'on') return ctx.setCamera(m.on === true); // Camera's switch: loads it, or stops it
      if (m && m.do === 'from') return ctx.setCameraFrom && ctx.setCameraFrom(m.id); // Camera from: whose camera shows here
      const { camShare: c, vcam } = ctx.cam();
      if (!c || !m || typeof m !== 'object') return;
      const allowed = async () => {
        const { systemPreferences } = require('electron');
        const st = systemPreferences.getMediaAccessStatus('camera');
        return st === 'granted' || (st === 'not-determined' && systemPreferences.askForMediaAccess('camera'));
      };
      if (m.do === 'view') { if (typeof m.id === 'string' && c.setFrom) c.setFrom(m.id); c.view(m.show === true); } // id: the camera picked at the top; show: its window too
      else if (m.do === 'close') c.closeView();
      else if (m.do === 'share') c.setShare(m.on === true, allowed);
      else if (m.do === 'device') c.setDevice(m.id);
      else if (m.do === 'shareTo') c.setShareTo(m.to); // who may see it: 'all' or [ids]
      else if (m.do === 'stop') c.stopSending(typeof m.id === 'string' ? m.id : undefined); // one computer viewing it, or all
      else if (m.do === 'devices') c.listDevices();
      // Camera › Virtual camera (shared/vcam.js).
      else if (m.do === 'virtual' && vcam) vcam.setOn(m.on === true);
      else if (m.do === 'vcamRemove' && vcam) vcam.remove();
      else if (m.do === 'vcamTarget' && vcam) vcam.setTarget(m.target);
      else if (m.do === 'rotate' && vcam) vcam.turn();
      else if (m.do === 'mirror' && vcam) vcam.setMirror(m.on === true);
    },
    // ReZume tab (shared/rezume.js): loaded when it's first turned on; here only with one phone (shared/rezume-solo.js).
    setRezume(m) {
      if (!m || typeof m !== 'object') return;
      settings.rezume = require('../../shared/rezume.js').normalize({ ...settings.rezume, ...m });
      save();
      const r = ctx.rezume();
      if (r) r.apply();
      else ctx.loadRezume();
    },
    rezumeDo(m) {
      if (m && m.a === 'with' && ctx.rzSolo) return void ctx.rzSolo.choose(typeof m.id === 'string' ? m.id.slice(0, 64) : ''); // the device ReZume is with (shared/rezume-solo.js)
      const r = ctx.rezume();
      if (!r || !m) return;
      if (m.a === 'take') r.take();
      else if (m.a === 'dismiss') r.dismiss();
      else if (m.a === 'push') r.push();
      else if (m.a === 'allow' && typeof m.app === 'string') r.allow(m.list, m.app, m.on === true);
      else if (m.a === 'forget') r.forget(m.list, typeof m.app === 'string' ? m.app : '');
    },
    // "Share sound with the screen" (Display › Mac → PC).
    setScreenSound(on) {
      settings.sharing.audio = !!on;
      save();
      ctx.stream.restart('screen sound');
    },
    // "Join every device automatically" (autojoin.js): off = no introductions asked, granted or accepted.
    // The matrix (shared/ui-matrix.js): one of this Mac's own cells, its pair with a device one way. The
    // selected device's pair is the settings (pairsync-mesh.js tells it), any other's its saved pair
    // (shared/consent.js tells it).
    // Notifications › Across devices: any cell, set where each end keeps it (shared/mesh-edges.js setCell).
    setCell(o) {
      const e = ctx.edges && ctx.edges();
      const { from, to, feature, on } = o || {};
      if (e && typeof from === 'string' && typeof to === 'string' && typeof feature === 'string' && typeof on === 'boolean') e.setCell(from, to, feature, on);
      pushState();
    },
    setConsent(o) {
      const c = ctx.consent && ctx.consent();
      const F = require('../pairsync').FEATURES;
      const { id, feature, dir, on } = o || {};
      if (!c || typeof id !== 'string' || !F[feature] || !F[feature][dir] || typeof on !== 'boolean') return;
      if (ctx.hub && id === ctx.hub.selectedId) return ctx.syncAction && ctx.syncAction(feature, dir, on);
      c.set(id, feature, dir, on);
      pushState();
    },
    // Biometric unlock from this Mac (shared/unlock-client.js): Unlock other computers, and Unlock.
    unlocker(o) {
      const u = ctx.unlocker && ctx.unlocker();
      if (!u || !o || typeof o !== 'object') return;
      const { op, arg } = o;
      if (op === 'on') u.setOn(arg === true);
      else if (op === 'unlock') u.want(String(arg));
      else if (op === 'unlockAll') u.wantAll(Array.isArray(arg) ? arg.map(String) : []); // a mesh manager: one after another
    },
    setMesh(partial) {
      setGroup('mesh', partial);
      if (settings.mesh.autoJoin !== false && ctx.autoJoin) ctx.autoJoin.schedule();
    },
    setApp(partial) {
      setGroup('app', partial);
      ctx.login.apply(settings.app.openAtLogin);
      ctx.updateAwake();
      if (ctx.applyLocalApi) ctx.applyLocalApi(); // General › Local API
    },
    setProximityLock(on) {
      if (typeof on !== 'boolean') return;
      settings.app.proximityLock = on;
      if (!on) ctx.proximityLock?.cancel();
      save();
    },
    setUpdates(partial) {
      setGroup('updates', partial);
      if (partial && typeof partial.install === 'boolean') ctx.updates.setInstall(partial.install);
      ctx.updates.start();
    },
    skipUpdate(version) {
      if (ctx.updates && ctx.updates.skip) ctx.updates.skip(version);
    },
    unskipUpdate() {
      if (ctx.updates && ctx.updates.unskip) ctx.updates.unskip();
    },
    checkUpdates() {
      ctx.updates.check(true);
    },
    openUpdate() {
      ctx.updates.open();
    },
    openLink(key) { // About page: only its own links, and the log folder
      if (key === 'logs') require('../../shared/applog.js').open();
      else if (Object.hasOwn(LINKS, key)) shell.openExternal(LINKS[key]);
    },
    setKeys(partial) {
      setGroup('keys', partial);
      ctx.kvm.config(); // the hotkey lives in the helper
    },
    setClipboard(partial) {
      setGroup('clipboard', partial);
      ctx.clipboard.applySettings();
    },
    copyHistory(index) {
      ctx.clipboard.copyHistory(Number(index));
    },
    // Recent's Open / Email / Call (shared/clipact.js): from the app's own copy of the item.
    openClip(index) {
      const h = (ctx.clipboard.history || [])[Number(index)];
      const a = h && !h.image && require('../../shared/clipact.js').of(h.text);
      if (a) shell.openExternal(a.url);
    },
    clearHistory() {
      ctx.clipboard.clearHistory();
    },
    // Calls, Messages and Photos (shared/phonehub.js, loaded the first time it's used).
    hub(r) {
      ctx.phoneHub().act(r);
    },
    // Overview: the selected device's controls (shared/devctl.js).
    deviceDo(c) {
      if (c && typeof c === 'object' && ctx.devctl && ctx.devctl()) ctx.devctl().do(c);
    },
    // General › Overview: what Overview shows.
    setOverview(o) {
      if (!o || typeof o !== 'object') return;
      const cur = settings.ui.overview || {};
      for (const k of ['media', 'qs', 'notifs', 'apps', 'clipboard', 'files']) if (typeof o[k] === 'boolean') cur[k] = o[k];
      settings.ui.overview = cur;
      store.saveSettings(settings);
      ctx.pushState();
    },
    // Messages: WhatsApp, Telegram and Instagram there too.
    setChats(on) {
      settings.ui.chats = on === true;
      store.saveSettings(settings);
      if ((ctx.chats && ctx.chats())) (ctx.chats && ctx.chats()).sync();
      ctx.pushState();
    },
    // A phone chat's notification answered here (its own Reply).
    // Keep history: {do: 'set', save, days} | {do: 'unlock', what} | {do: 'clear'} (shared/histkeeper.js).
    history(r) {
      if (ctx.history && r && typeof r === 'object') ctx.history.act(r);
    },
    // Connection › Wireless debugging › Pair with a QR code: on while shown.
    adbQr(on) {
      if (ctx.adbQr) ctx.adbQr(on === true);
    },
    notifReply(r) {
      if (r && typeof r === 'object' && r.chat) return void ((ctx.chats && ctx.chats()) && (ctx.chats && ctx.chats()).reply(String(r.chat), r.text, r.image, r.remove === true)); // a chat app's conversation (shared/chats.js)
      if (!r || typeof r !== 'object' || !ctx.notifs) return;
      if (r.dismiss) return void ctx.notifs.dismiss(String(r.id || '')); // Overview's × (shared/notifacts.js)
      if (Number.isInteger(r.act)) return void ctx.notifs.act(String(r.id || ''), r.act); // one of its buttons
      ctx.notifs.reply(String(r.id || ''), r.text);
    },
    // General › Appearance: { style }, { theme } and/or { accent } ('' follows the system); local only.
    setLook(o) {
      if (!o || typeof o !== 'object') return;
      const Look = require('../../shared/look.js');
      if (typeof o.style === 'string') settings.ui.style = Look.style(o.style);
      if (typeof o.theme === 'string') settings.ui.theme = Look.theme(o.theme);
      if (typeof o.accent === 'string') settings.ui.accent = Look.accent(o.accent);
      store.saveSettings(settings);
      if (ctx.onLook) ctx.onLook();
      ctx.pushState();
    },
    setLanguage(language) {
      if (!require('../../shared/i18n.js').savedLanguage(language) || settings.ui.language === language) return;
      settings.ui.language = language;
      save();
      if (ctx.onLanguage) ctx.onLanguage();
    },
    setTab(tab) {
      if (!TABS.includes(tab)) return;
      settings.ui.tab = tab;
      store.saveSettings(settings); // no state push needed; the window already shows it
    },
    pairRespond(allow) {
      ctx.pairing.respond(!!allow);
    },
    forget(deviceId) {
      if (ctx.batteryAlerts && deviceId != null && deviceId !== '') ctx.batteryAlerts.forget(String(deviceId));
      // The device can be a saved host or a paired client.
      ctx.proximityLock?.forget(String(deviceId));
      if (ctx.link.hosts.some((h) => h.id === String(deviceId))) return ctx.link.forget(String(deviceId));
      ctx.pairing.forget(String(deviceId));
      ctx.terminal.forget(String(deviceId));
    },
    openSettings(kind) {
      if (SETTINGS_URLS[kind]) shell.openExternal(SETTINGS_URLS[kind]);
    },
    relaunch() {
      app.relaunch();
      app.quit(); // not exit: before-quit sends the cursor home and lets the helper release input
    },
    setMulti(on) {
      require('../multi').set(on === true); // Multi-device off: TwinDesk restarts one to one
    },
  };

  ipcMain.handle('getState', () => ctx.state);
  // Debug (shared/debug-start.js, docs/debug.md): ask any device of the mesh; who may debug this Mac.
  ipcMain.handle('debugAsk', (_e, to, op, args) => {
    const d = ctx.dbg && ctx.dbg();
    if (!d || typeof to !== 'string' || typeof op !== 'string') return { ok: false, error: 'off' };
    return d.ask(to, op, args && typeof args === 'object' ? args : {});
  });
  ipcMain.handle('setDebug', (_e, o) => {
    const d = ctx.dbg && ctx.dbg();
    if (!d || !o || typeof o !== 'object') return;
    settings.mesh.debug = require('../../shared/debug-settings.js').normalizeDebug(d.next(o));
    save();
  });
  ipcMain.handle('debugShow', (_e, p) => { // only what Debug kept, in the log folder
    const path = require('path');
    const dir = require('../../shared/applog.js').dir();
    if (typeof p === 'string' && dir && path.resolve(p).startsWith(path.resolve(dir) + path.sep)) shell.showItemInFolder(p);
  });
  // Mesh managers (shared/mesh-mgr.js): manager mode, a computer added or let go, its Biometric unlock,
  // this Mac's answer to a manager, Revoke, and a manager's action.
  // Camera & Controller › Controller (shared/pad-share.js): a window's controller state, and the settings.
  ipcMain.on('padState', (_e, st) => { const p = ctx.padShare && ctx.padShare(); if (p) p.fromWindow(st); });
  ipcMain.handle('setPads', (_e, o) => { const p = ctx.padShare && ctx.padShare(); if (p && o && typeof o === 'object') p.set(o); });
  ipcMain.handle('setMgr', (_e, o) => {
    const m = ctx.mgr && ctx.mgr();
    if (!m || !o || typeof o !== 'object') return null;
    const id = (v) => (typeof v === 'string' ? v : '');
    if (typeof o.on === 'boolean') m.setOn(o.on);
    if (o.pick && typeof o.pick.on === 'boolean') m.pick(id(o.pick.id), o.pick.on);
    if (o.unlock && typeof o.unlock.on === 'boolean') m.setUnlock(id(o.unlock.id), o.unlock.on);
    if (o.answer && typeof o.answer.yes === 'boolean') m.answer(id(o.answer.mgr), String(o.answer.perm), o.answer.yes);
    if (o.revoke) m.revoke(id(o.revoke));
    pushState();
    if (o.act) return m.act(id(o.act.to), String(o.act.do));
    return null;
  });
  // Terminal in Multi-device (shared/ui-term-mesh.js): a nickname, or the answer to a computer asking for a shell here.
  ipcMain.handle('termMesh', (_e, o) => {
    if (!o || typeof o !== 'object') return null;
    if (o.nick && typeof o.nick.id === 'string') {
      const n = ctx.termNames && ctx.termNames();
      const r = n ? n.set(o.nick.id, String(o.nick.name || '')) : { ok: false, why: 'bad' };
      pushState();
      return r;
    }
    if (o.answer && typeof o.answer.id === 'string') {
      const ps = ctx.pairSync && ctx.pairSync();
      if (ps) ps.answer(o.answer.id, 'terminal', o.answer.yes === true);
      pushState();
    }
    return null;
  });
  ipcMain.handle('qrPair', () => (ctx.qrPair ? ctx.qrPair() : { url: '' })); // Connection: the phone pairing QR code's link
  ipcMain.handle('phoneAssets', () => ctx.phone.assetsView());
  ipcMain.handle('deckApps', () => (ctx.deck ? ctx.deck.apps().catch(() => []) : [])); // the Deck page's app picker
  ipcMain.handle('deckPick', (_e, o) => (async () => { // the Deck page: a file, folder or script for a tile (its path stays here)
    const { BrowserWindow } = require('electron');
    const kind = o && o.kind;
    const r = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow() || undefined, {
      properties: kind === 'folder' ? ['openDirectory'] : kind === 'any' ? ['openFile', 'openDirectory'] : ['openFile'],
      ...(kind === 'script' ? { title: 'Choose a script', buttonLabel: 'Choose' } : {}),
    });
    return r.canceled || !r.filePaths.length ? '' : r.filePaths[0];
  })(o));
  ipcMain.handle('deckRun', (_e, a) => (ctx.deck && a && typeof a === 'object' ? ctx.deck.exec(a).then(() => ({ ok: true }), (e) => ({ ok: false, why: e.message })) : { ok: false })); // Try
  // Audio › the mixer (shared/ui-sound-mix.js): a device's speakers for our sound (out) or ours for its (in);
  // this Mac's own speakers' volume (read with no level).
  ipcMain.handle('soundRoute', (_e, o) => { if (o && typeof o === 'object' && typeof o.id === 'string' && (Array.isArray(o.outs) || o.outs === null)) ctx.audio.setRoute(o.id, o.dir === 'in' ? 'in' : 'out', o.outs); pushState(); });
  ipcMain.handle('soundSpeakers', (_e, list) => { if (Array.isArray(list) && list.length <= 32 && ctx.audio && ctx.audio.setSpeakers) ctx.audio.setSpeakers(list); }); // this Mac's speakers, from the settings window
  ipcMain.handle('soundOwn', (_e, v) => { const o = ctx.ownSound; if (!o) return; if (Array.isArray(v) && v.length <= 8) o.set(v); else if (v && typeof v === 'object' && typeof v.mode === 'string') o.mode(v.mode); else if (v && typeof v === 'object' && typeof v.def === 'string') o.setDefault(v.def); }); // This Mac: System default or Choose devices (shared/own-sound.js)
  ipcMain.handle('soundVolume', (_e, level) => require('../../shared/sound-local.js').volume('darwin', ctx.helper, level).catch(() => ({ volume: null })));
  ipcMain.handle('deckState', (_e, obs) => (ctx.deck ? ctx.deck.state(obs === true, obs === 'mix').catch(() => ({})) : {})); // its sound, Bluetooth and display pickers (OBS's: obs)
  // OBS Studio's port and password (#394): Multi-device had no way to set them, so Connect did nothing.
  ipcMain.handle('deckObs', () => (ctx.deck ? ctx.deck.obsConfig() : null));
  ipcMain.handle('deckSetObs', (_e, v) => (ctx.deck && v && typeof v === 'object' ? ctx.deck.setObs(v) : { on: false })); // → OBS's state with them
  ipcMain.handle('deckGitHub', (_e, v) => (ctx.deck && ctx.deck.gitHub && (v === undefined || v === null || typeof v === 'string') ? ctx.deck.gitHub(v) : { hasToken: false })); // the Build widget's GitHub token: kept sealed, never sent back
  ipcMain.handle('phoneListCameras', () => (ctx.phone && ctx.phone.bridge ? ctx.phone.bridge.listCameras() : [])); // Camera: the phone's cameras
  for (const [name, fn] of Object.entries(actions)) ipcMain.on(name, (_e, arg) => fn(arg));
  return actions;
}

module.exports = { setupIpc, TABS };