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.

57.1 KB
Raw Blame
// TwinDesk — a Mac and a Windows PC that work as one.
// Copyright (C) 2026 inukaasith. Licensed under the GNU GPL v3 (see LICENSE).
//
// Protocol v1 — single source of truth for both apps.
// Works as a CommonJS module in main processes (require('../shared/protocol.js'))
// and as a plain <script> in renderers (window.MacShareProtocol).
// The crypto helpers exist only where Node's crypto is available (main processes).
(function (root) {
  const P = {
    PROTOCOL_VERSION: 1,
    PORT: 47800, // WSS control channel; the host listens
    DISCOVERY_PORT: 47801, // UDP beacons, probes and invites; every app sends and listens
    BEACON_MS: 2000,
    PROBE_MS: 10000, // broadcast probe while not connected
    PROBE_REPLY_MS: 1500, // a unicast probe without a reply by then = nobody there
    DEVICE_STALE_MS: 10000, // found device dropped after this much silence
    OS: { MAC: 'mac', WIN: 'win', LINUX: 'linux', ANDROID: 'android', IOS: 'ios' },
    // A phone is a full peer in the one session: it connects only when asked (the Mac's phone
    // tile, its own Connect button, an invite) or to resume a session that just dropped, and it
    // replaces the computer. Computers are refused (busy) while it holds the session and for
    // PHONE_GRACE_MS after it drops, so a Wi-Fi blip doesn't hand the session back.
    // Capable Macs allow a durable exact-phone return (hello rc:1), never a takeover. The phone
    // keeps the last authenticated Mac until Stop/Forget/replacement; the Mac independently keeps
    // its last Android owner. Legacy hosts still reject hello+resume instead of taking a session.
    PHONE_GRACE_MS: 30000,
    PING_MS: 1000,
    TIMEOUT_MS: 8000, // close the session after this much silence (8 s: a busy or throttled computer can miss a ping or two, #74)
    HELLO_TIMEOUT_MS: 4000, // no `welcome` this long after hello = try again (an answer comes at once; not the silence limit)
    // Multi-device only (docs/mesh.md): many devices at once. A link that is selected, driving or being
    // driven keeps PING_MS/TIMEOUT_MS; the others are checked more rarely so ten links cost little.
    MAX_DEVICES: 10,
    IDLE_PING_MS: 5000,
    IDLE_TIMEOUT_MS: 15000,
    INBOUND_WAIT_MS: 5000, // two computers that hold each other as hosts: the larger id waits this long for the other to dial
    POOL_SEEN_LIMIT: 200, // (origin, seq) pairs remembered per pool for dedupe
    POOL_MAX_HOPS: 9, // one less than MAX_DEVICES: enough for a chain of ten (duplicates are dropped, so no storms)
    BLE_TIMEOUT_MS: 20000, // the same through Bluetooth, where one big message takes seconds
    PAIR_TIMEOUT_MS: 60000,
    UNAUTH_TIMEOUT_MS: 70000, // Mac closes sockets that never authenticate
    RECONNECT_MS: [1000, 2000, 3000], // Windows: then keep using the last value
    MAX_PAYLOAD: 16 * 1024 * 1024,
    SAS_LABEL: 'macshare-sas-v1',

    // Mouse & keyboard sharing
    KVM_TAKE_TIMEOUT_MS: 1000, // owner goes home if no kvm.accept by then
    KVM_SILENCE_MS: 2000, // while driving/driven: no message from the peer for this long = link lost
    KVM_SILENCE_BLE_MS: 6000, // the same through Bluetooth (a slower, burstier link)
    KVM_MOVE_BLE_MS: 16, // through Bluetooth: cursor moves summed and sent at most this often
    KVM_BLE_BACKLOG: 512, // … and held (still summed) while this many bytes wait for the radio
    KVM_IP_BACKLOG: 64 * 1024, // on the network: moves held (still summed) while this many bytes wait on the socket
    KVM_MOVE_MAX_WAIT_MS: 16, // … but one goes at least this often (behind a big message the pointer still moves)
    KVM_CROSS_COOLDOWN_MS: 250, // no new crossing this soon after the last one, either way (the helpers' edges)
    KVM_EDGE_DWELL_MS: 150, // an edge push crosses only once it lasted this long (with Edge resistance): the end of a quick flick doesn't
    HELPER_KEEPALIVE_MS: 500, // main -> helper keepalive while capturing
    HELPER_DEADMAN_MS: 1500, // helper stops capturing by itself after this much keepalive silence
    RESISTANCE_PX: 120, // default push through an edge before crossing
    DOUBLE_TAP_MS: 400, // hotkey double-tap window
    // The hotkey (double-tap = mouse and keyboard back home).
    // Default Right Alt / Right Option on every OS; settings.keys.hotkey picks one of HOTKEYS.
    HOTKEY_MAC: 'AltRight', // Right Option
    HOTKEY_WIN: 'AltRight', // Right Alt (was Right Ctrl)
    // Right, left, or either side ("Alt" = both Alt/Option keys).
    HOTKEYS: ['AltRight', 'AltLeft', 'Alt', 'ControlRight', 'ControlLeft', 'Control',
      'ShiftRight', 'ShiftLeft', 'Shift', 'MetaRight', 'MetaLeft', 'Meta'],
    CLIP_MAX_BYTES: 256 * 1024, // clipboard text limit (UTF-8)
    CLIP_IMAGE_MAX_BYTES: 10 * 1024 * 1024, // clipboard picture limit (PNG bytes, before base64)
    CLIP_IMAGE_PART_BYTES: 256 * 1024, // raw bytes per clip.image.part (base64 on the wire)
    CLIP_SKEW_MS: 10 * 60 * 1000, // a copy time further ahead of our clock than this is clamped (a clock that wrong must not win for ever)
    FILE_CHUNK_BYTES: 64 * 1024, // raw bytes per file.chunk (base64 on the wire)
    FILE_MAX_BYTES: 16 * 1024 ** 4, // largest file sent or received (16 TiB: no real limit; was 4 GiB, #143)
    SIDES: ['left', 'right', 'top', 'bottom'],

    // Control message types (field `t`)
    T: {
      BEACON: 'beacon', // UDP {v, id, name, port, fp, os, role: 'host'}
      PROBE: 'probe', // UDP {v, id}: answer with your beacon, unicast to the sender
      INVITE: 'invite', // UDP {v, id, name, os, port, fp}: a Mac asks a PC to pair/connect to it
      // pairing
      PAIR_START: 'pair.start',
      PAIR_NONCE: 'pair.nonce',
      PAIR_REVEAL: 'pair.reveal',
      PAIR_CONFIRM: 'pair.confirm',
      PAIR_OK: 'pair.ok',
      PAIR_CANCEL: 'pair.cancel',
      // session
      HELLO: 'hello', // + {rc:1, resume:'0'} is a non-takeover reclaim (shared/reclaim.js); plain hello still takes a phone's session
      WELCOME: 'welcome',
      ERROR: 'error',
      PING: 'ping',
      PONG: 'pong',
      BYE: 'bye', // guest->host: Disconnect on purpose (a phone gets no grace to resume; computers may connect at once)
      // screen sharing
      STREAM_INFO: 'stream.info',
      STREAM_STOP: 'stream.stop',
      // screen.state input (optional) reports whether the sharer currently accepts screen input.
      STREAM_INPUT: 'stream.input', // Mac -> Windows: {on} whether the Mac accepts in.* ("Receive input")
      RTC_OFFER: 'rtc.offer',
      RTC_ANSWER: 'rtc.answer',
      RTC_ICE: 'rtc.ice',
      RTC_DETAIL: 'rtc.detail', // Android -> desktop: {session, height}; an advertised offer tier, or 0 for the baseline
      // input inside the Monitor 2 window (absolute, normalized), Windows -> Mac. From a phone's
      // stylus, in.mm/md/mu carry `pen` (P.penOf): the helpers inject a tablet pen; without it, a mouse
      IN_MOVE: 'in.mm',
      IN_DOWN: 'in.md',
      IN_UP: 'in.mu',
      IN_WHEEL: 'in.wh',
      IN_KEY_DOWN: 'in.kd',
      IN_KEY_UP: 'in.ku',
      // real touch (a viewer's Touch/Direct mode, when the sharer's screen.state says touch: true):
      // {p: [[id 0–9, x, y], …]} every finger touching now, normalized; p: [] = all lifted (P.touchesOf)
      IN_TOUCH: 'in.tc',
      // mouse & keyboard sharing across the two physical screens (relative), either way
      KVM_LAYOUT: 'kvm.layout',
      KVM_TAKE: 'kvm.take',
      KVM_ACCEPT: 'kvm.accept',
      KVM_REFUSE: 'kvm.refuse',
      KVM_RELEASE: 'kvm.release',
      // driven->owner {route, offset?, drag?}: the input goes home. With the left button still held in
      // a file drag, `drag` carries it on there: {back: id} the owner's own drag.start `id` came back
      // (its files are on the owner), {count} the driven side's own files follow as a drag.start + files
      KVM_HOME: 'kvm.home',
      KVM_LINK: 'kvm.link', // either {on}: mouse and keyboard sharing switched on/off (hotkey double-tap); the other side follows
      KVM_LOCK: 'kvm.lock', // either {on}: the cursor is locked on the device it is on (shared/cursorlock.js); sent only while one drives the other
      KVM_DISPLAYS: 'kvm.displays', // either {displays: [{id, x, y, w, h, scale, primary, name}]}: our monitors (shared/kvm-geom.js), on connect and when they change
      KVM_IDENTIFY: 'kvm.identify', // either {}: show each monitor's number on it for a moment (the Cursor tab's Identify)
      KVM_CAPS: 'kvm.caps', // either {on}: my Caps Lock as I hand my input over (take, or home); the other side turns its own that way (shared/capsync.js, #131)
      KVM_NEXT: 'kvm.next', // multi-device: {route, to, side, offset}: a device we drive reached an edge that leads to device `to` (docs/mesh.md)
      K_MOVE: 'k.mm',
      K_CROSSING_MODIFIERS: 'k.mod', // physical modifier state for a compatible peer's return edge
      K_DOWN: 'k.md',
      K_UP: 'k.mu',
      K_WHEEL: 'k.wh',
      // {code} the key's place; ch: the a–z letter it types on the sender's layout (shortcuts by letter);
      // tx (k.kd): what it types there on another alphabet's layout (ж, ක, ඛ with Shift), typed as it is
      // where the key types something else; im (k.kd): the language of the input method typed with there
      // (ja, zh-Hans, ko), whose own one the other side switches to (shared/keylayout.js)
      K_KEY_DOWN: 'k.kd',
      K_KEY_UP: 'k.ku',
      // A trackpad gesture by what it means, done natively by the driven computer:
      // {g: 'zoom' (v = magnification step, + = in) | 'smartZoom' | 'rotate' (v degrees) | 'back' |
      //  'forward' | 'overview' (Mission Control / Task View) | 'appWindows' | 'desktop' |
      //  'spaceLeft' | 'spaceRight' (the desktop to the left / right) | 'launcher', phase?: 'begin'|'change'|'end'}
      K_GESTURE: 'k.ge',
      // clipboard text
      CLIP: 'clip',
      CLIP_REQUEST: 'clip.request',
      CLIP_POLICY: 'clip.policy', // either way: {accept, images, queue} — whether this side applies clip (and clip.image) from the other
      CLIP_QUEUE: 'clip.queue', // either way: {items: [{text, at}]}: copies made while the other was away, for its Recent (shared/clipqueue.js); sent only to a side whose clip.policy has queue
      // The latest copy wins (shared/clipsync.js; Multi-device's clipboard for now): `clip` carries {ts, o}:
      // when the copy happened (a hybrid logical clock, ms) and on which device. An older item never replaces a newer one.
      CLIP_IMAGE: 'clip.image', // either way: {id, ts, o, w, h, png: base64} an image on the clipboard
      // … one-to-one (shared/clipimage.js): {id, w, h, bytes, parts, shot?} then `parts` clip.image.part,
      // sent only to a side whose clip.policy says images, never through Bluetooth; shot: a screenshot just taken
      CLIP_IMAGE_PART: 'clip.image.part', // either way {id, i, data (base64)}: piece i of the picture
      CLIP_LATEST: 'clip.latest', // either way, after welcome: {ts, o, kind: 'text'|'image'|'files'} what this side holds as the newest copy
      // roadmap,
      AUDIO_POLICY: 'audio.policy', // W->M {accept}: the PC plays the Mac's sound
      SSH_KEY: 'ssh.key', // W->M {pub}
      SSH_INFO: 'ssh.info', // M->W {enabled, user, port, hostKeys, why?}
      SSH_FORGET: 'ssh.forget', // W->M
      FILE_OFFER: 'file.offer', // W->M {id, name, size, x?, y?, index, count, cont?, to?} (to: a phone's batch for another device of the mesh, passed on, shared/files-relay.js) (cont: the first batch's id, the rest of a paused or cut-off Send files batch, shared/outbox.js)
      FILE_ACCEPT: 'file.accept', // M->W {id}
      FILE_REFUSE: 'file.refuse', // M->W {id, why}
      FILE_CHUNK: 'file.chunk', // W->M {id, seq, data (base64)}
      FILE_END: 'file.end', // W->M {id, sha256}
      FILE_DONE: 'file.done', // M->W {id, ok, path?, error?}
      FILE_CANCEL: 'file.cancel', // either {id, pause?} (pause: the sender paused its batch; it ends quietly)
      // TwinDesk Drive (docs/drive.md, shared/drive-link.js): one folder kept the same on every device
      // that turns it on. An app without it never answers drive.hello, so it never starts.
      DRIVE_HELLO: 'drive.hello', // either {v: 1, have?: {e, n}, again?}: Drive is on here (have: where I last had all of yours; again: send it once more)
      DRIVE_INDEX: 'drive.index', // either {entries: [{p, s, m, h, d, v, by}], last, upto?: {e, n}}: what changed since the other's have (or everything), in parts
      DRIVE_UPDATE: 'drive.update', // either {entries, r?: {e, from, to}}: what changed here since (r: those changes' numbers)
      DRIVE_WANT: 'drive.want', // host->guest {id, p, h}: PUT this file to /twindesk/drive/u?id=
      DRIVE_GONE: 'drive.gone', // guest->host {id}: that version isn't here any more
      // Fast files (shared/fastfile.js), only between two apps that both said so (hello {fx: 1},
      // welcome {fx: token}) on Wi-Fi or a cable: the bytes go over HTTPS on PORT instead of file.chunk.
      FILE_PULL: 'file.pull', // host->guest {id}: come and get it (GET); guest->host {id, failed: true}: couldn't
      // drag across the edge: a native drag on the receiver, files + folders
      DRAG_START: 'drag.start', // owner->receiver {drag, items: [{name, dir, size}], dirs: [rel], list: [{rel, size}], files, bytes}
      DRAG_CANCEL: 'drag.cancel', // owner->receiver {drag}
      DRAG_END: 'drag.end', // receiver->owner {drag, result: 'dropped'|'cancelled'|'failed', where?}
      DRAG_POLICY: 'drag.policy', // both {accept}: this side takes drags across the edge (assume true until told)
      // Notifications, Send files, copy/paste files with shortcuts
      NOTIF: 'notif', // either {id, app, appName, title, subtitle, body, at}: a notification on the sender
      NOTIF_POLICY: 'notif.policy', // either {accept}: this side shows the other's notifications
      TASK_ALERT_POLICY: 'task.alert.policy', // phone -> computer {on}: task alerts are allowed on this socket (shared/task-alerts.js)
      TASK_ALERT: 'task.alert', // computer -> phone {id, title, ok}: a command run through twindesk-notify ended; no command or output
      FCLIP_OFFER: 'fclip.offer', // either {id, items: [{name, dir, size}], files, bytes}: files copied with the shortcut
      FCLIP_PASTE: 'fclip.paste', // either {id}: paste them here now (the copier then sends file.offer drop:'paste')
      FCLIP_KEY: 'fclip.key', // owner->driven {action:'copy'|'paste'}: the copy/paste shortcut pressed while driving it — do it there
      FCLIP_GONE: 'fclip.gone', // either {id}: nothing to paste any more (files moved, or a newer copy)
      FILES_DONE: 'files.done', // receiver->sender {batch, ok, where?, files}: a Send/paste batch landed
      // roadmap, (PC -> Mac media)
      RTC2_OFFER: 'rtc2.offer', // W->M {session, sdp, kind}
      RTC2_ANSWER: 'rtc2.answer', // M->W {session, sdp}
      RTC2_ICE: 'rtc2.ice', // either {session, candidate}
      RTC2_STOP: 'rtc2.stop', // W->M {session}
      // App-window sessions (kind 'window') also carry `win`: 'send' from the window's sender
      // (offer, its ice, stop), 'view' from the viewer (answer, its ice). Two PCs both send and
      // view windows, so this says whose session a number is; swapRole leaves these alone.
      AUDIO_OFFER: 'audio.offer', // sender->receiver {dir:'m2w'|'w2m', session, sdp}
      AUDIO_ANSWER: 'audio.answer', // receiver->sender {dir, session, sdp}
      AUDIO_ICE: 'audio.ice', // either {dir, session, candidate}
      AUDIO_STOP: 'audio.stop', // sender->receiver {dir}
      AUDIO_ROUTE: 'audio.route', // sender->receiver {outs?: [{id, vol}], sync?: ms}: which of the receiver's speakers, and Keep speakers in sync (shared/sound-route.js)
      AUDIO_OUTS: 'audio.outs', // receiver->sender {outs: [{id, name}], route: [{id, vol}], lat}: its speakers, the route kept, the delay heard (ms)
      // Audio › Microphone (shared/mic.js): each side's microphone on the other, either way on its own
      MIC_POLICY: 'mic.policy', // either {accept, ask?}: it uses the other's microphone; ask: send yours back (just loaded)
      MIC_OFFER: 'mic.offer', // sender->receiver {session, sdp}
      MIC_ANSWER: 'mic.answer', // receiver->sender {session, sdp}
      MIC_ICE: 'mic.ice', // either {session, to: 'recv'|'send', candidate}
      MIC_STOP: 'mic.stop', // sender->receiver {}
      // Camera sharing between two computers (shared/camshare.js, the Camera tab): one's camera in a
      // window on the other, WebRTC set up through these, the picture straight between them.
      CAM_POLICY: 'cam.policy', // either way, after welcome and on change {share}: this side lets the other see its camera
      CAM_OPEN: 'cam.open', // viewer->sharer: show me your camera (it answers cam.offer, or cam.state {status: 'refused'})
      CAM_CLOSE: 'cam.close', // either way: the viewer's window closed, or the sharer stopped
      CAM_OFFER: 'cam.offer', // sharer->viewer {sdp}
      CAM_ANSWER: 'cam.answer', // viewer->sharer {sdp}
      CAM_ICE: 'cam.ice', // either way {from: 'send'|'view', candidate}
      CAM_STATE: 'cam.state', // sharer->viewer {status: 'starting'|'live'|'failed'|'refused', error?}
      SCREEN_POLICY: 'screen.policy', // either, viewer->sharer {accept, width?, height?, multi?}: a viewer is open and wants the picture (senders capture only while it is true). multi (optional, Multi-device Windows and Linux): this device opens a window per extra stream. Extra streams (another screen of the same sharer, shared/screen-ch.js) carry ch 1…3 on every screen.*, stream.*, rtc.*, rtc2.* and in.* message; no ch is stream 0, today's. A sharer sends ch only to a viewer that said multi. screen.state may carry place (optional): the viewer's display id that picture fills
      SCREEN_CTL: 'screen.ctl', // either, viewer->sharer {share?, mode?: 'mirror'|'extend', displayId?, close?}: start/stop or switch the other's sharing. displayId (optional, one-to-one Mac) mirrors that real display; absent, or mode extend, keeps today's path. An unknown id does not change which screen is shared. A pick while this Mac's apps hold the virtual display is not stored. Multi-device ignores displayId: one capture and one input target are shared, and a per-device off or display choice is the owner's. close (with share false: the phone viewer's Close) stops it even without remote
      SCREEN_STATE: 'screen.state', // either, sharer->viewer {on, mode, remote, modes, displays?, displayId?, spaces?, spaceHold?, desktops?}: what this side shares; remote = it takes screen.ctl. displays (optional, one-to-one) are the real screens, omitted while apps hold the virtual display and omitted in Multi-device; displayId is the one mirrored now, and is omitted while extending. spaces (optional, Mac): true only when the display this viewer is being shown has its own previous or next desktop, accessibility is trusted, remote input is not paused, and a read-only check says every on-screen window belongs to a desktop that is current. False while a window from another desktop is still visible, or while accessibility cannot be used. spaceHold (optional, Mac): "accessibility" or "overview" while remote input is paused so a touch is not sent into Mission Control. Omitted when input is not paused. desktops (optional, Mac): a bounded catalog of allowed displays and the numeric desktop ids on each, which one this viewer is actually being shown, a revision, and the capture session of the picture being shown. The capture session is assigned when capture starts and is not itself a decoded frame. No window or app contents and no thumbnails. Multi-device lists only that viewer's display. Omitted by older apps, Windows, and Linux. False, omitted spaces, Windows, and Linux: the phone shows no previous/next desktop buttons
      SCREEN_SPACE: 'screen.space', // viewer->Mac. Previous/next stays {dir:'prev'|'next', displayId?}: the desktop beside the one on the display this viewer is being shown. displayId, when present, must be that display. An absolute choice is {displayId, spaceId, index, count, rev} and no dir: that desktop on the display this viewer is being shown when the message arrives. rev is the desktops catalog revision. The Mac reads again and refuses when that id is no longer at that index, or the revision does not match this view. It does not also change which display is captured. The display is the one at message receipt; a later change, including a return to the same id when a generation is available, is refused. A Mac that only knows dir replies why dir and does not move. Ignored by older apps, Windows and Linux. The Mac runs either form only for the authenticated session allowed to send stream input, and does not send Control-arrow. It does not open Mission Control while the composition check is not clean, accessibility is not trusted, or remote input is paused. The current desktop is not a press
      SCREEN_SPACE_RESULT: 'screen.space.result', // Mac->viewer {ok, why?, edge?:'first'|'last', dir?, already?}: the screen.space outcome. why spans: desktops are shared across displays, so this screen was not moved. why accessibility: the accessibility tree cannot be used, or input is paused because it cannot be read. why overview: input is paused while Mission Control is showing. why stale: the session or the desktop list changed before the press. already: that desktop was already current, so Mission Control was not opened. A viewer that does not know it ignores it
      SCREEN_DESKTOPS: 'screen.desktops', // viewer->Mac {epoch}: ask for a fresh desktop catalog. The Mac reads again only for the authenticated session allowed to send stream input, and publishes that read only when that session and the viewed display generation are still the ones the read started with. A read that misses either is not published. The reply is {ok, why?:'stale', epoch}. ok true means the catalog was published on screen.state. epoch is the viewer's and is echoed, so a late reply is not treated as a newer ask. Ignored by older apps, Windows, and Linux.
      SCREEN_PREVIEW_WANT: 'screen.preview.want', // viewer->Mac {on, epoch}. epoch is a positive integer up to 2^48-1 naming this sheet-open. on true asks for stills only while this viewer's Displays & desktops sheet is open, and only on the authenticated socket the message arrived on. The Mac captures no display without that ask, and an on true with no such epoch does not start one. on false carries that same epoch and cancels the ask, as do a closed sheet, the viewer leaving the foreground, sharing stopped, the screen locked, remote input revoked, a disconnect, or a replacement socket. Any of those drops an in-flight shot. Older apps, Windows, and Linux ignore it.
      SCREEN_PREVIEW: 'screen.preview', // Mac->viewer. One still JPEG of one display the desktop catalog already allows, for the space that display is on now: {epoch, displayId, spaceId, capture, viewGen, width, height, jpeg}. epoch is the sheet-open from screen.preview.want, and it is also on {clear:true} and on {unavailable:'os'|'permission'}. capture and viewGen are the picture's session and selection generation, not a decoded frame. jpeg is base64, at most 24 KB, and the long side is at most 480. The Mac takes it only while screen.preview.want is still on for this exact socket and that epoch, with one ScreenCaptureKit screenshot of that display on macOS 14. After the ask and before the reply, the same authenticated socket, capture session, view generation, current space, unlocked screen, and a fresh accessibility read of hidden Mission Control still have to hold. A visible or unreadable Mission Control is not hidden. It does not switch desktops to take the picture, and it does not use a thumbnail of every display. {clear:true} drops what this sheet-open stored. The viewer still applies clear and unavailable for that epoch after the sheet closes, so a lock or a stop can drop them. A JPEG is kept only while the viewer is still asking for that same epoch. After the sheet closes and opens again, or after a new link, an older epoch is dropped even when capture and viewGen still match. {unavailable:'os'|'permission'} means this Mac cannot take one: macOS 13 has no screenshot API here, or Screen Recording is not granted. No prompt is made. Older apps, Windows, and Linux ignore it. The bytes are memory on both sides for this connection.
      PAIR_SYNC: 'pair.sync', // either {feature, dir: 'out'|'in', on} | {key, value} (shared value, e.g. pace) | {all: {feature: {out, in}, values: {key: value}}} (host, after welcome): two-way switches shared per pair, dirs from the sender's side
      WOL_INFO: 'wol.info', // either {macs: ['aa:bb:cc:dd:ee:ff'], address}: how to wake this computer over the network
      SMB_OFFER: 'smb.offer', // sharer->other {share, user, password, port}
      SMB_REVOKE: 'smb.revoke', // sharer->other {share}
      SMB_STATE: 'smb.state', // other->sharer {share, mounted, error?}
      APPS_LIST: 'apps.list',
      APPS_RESULT: 'apps.result',
      APP_LAUNCH: 'app.launch',
      APP_LAUNCHED: 'app.launched',
      APP_WINDOWS: 'app.windows', // M->W {windows: [{wid, id, title, x, y, w, h}]} normalized rects
      APP_FOCUS: 'app.focus', // W->M {wid}
      APP_CLOSE: 'app.close', // W->M {wid}
      // PC apps on the Mac
      PAPP_POLICY: 'papp.policy', // M->W {accept}
      PAPPS_LIST: 'papps.list', // M->W
      PAPPS_RESULT: 'papps.result', // W->M {apps: [{id, name, icon}]}
      PAPP_LAUNCH: 'papp.launch', // M->W {id}
      PAPP_LAUNCHED: 'papp.launched', // W->M {id, ok, why?}
      PAPP_WINDOWS: 'papp.windows', // W->M {windows: [{wid, id, title, w, h, scale, popup?, owner?, x?, y?}]}
      PAPP_FOCUS: 'papp.focus', // M->W {wid}
      PAPP_CLOSE: 'papp.close', // M->W {wid}
      PAPP_SIZE: 'papp.size', // M->W {wid, w, h} physical px
      PAPP_RETURN: 'papp.return', // M->W {wid}: a window moved here (papp.windows moved: true) goes back, dragged past the edge home
      // A phone (os 'android') as the peer
      PHONE_INFO: 'phone.info', // phone->Mac {model, maker, sdk, release, battery?, charging?, colors: ['#rrggbb'], wallpaper?: data URL (small JPEG), app? (versionName), caps?: ['mirror.native', …] (what it can do without wireless debugging; an older app sends none)}
      PHONE_APPS_LIST: 'phone.apps.list', // Mac->phone
      PHONE_APPS: 'phone.apps', // phone->Mac {apps: [{id (package), name, icon (data URL PNG)}]}
      PHONE_POINTER: 'phone.pointer', // Mac->phone {on, x?, y?}: where the Mac's pointer is while it drives the phone (the app draws it)
      // Driving the phone without wireless debugging (shared/phoneinput.js): the phone applies the input itself
      PHONE_IN: 'phone.in', // computer->phone {a: 'd'|'m'|'u'|'s'|'k', …}: touch, scroll, key
      PHONE_INPUT: 'phone.input', // phone->computer {on}: it can apply phone.in (its Accessibility service is on)
      PHONE_INPUT_ASK: 'phone.input.ask', // computer->phone: the person wants to drive it: ask to switch that on
      PHONE_INPUT_VIA: 'phone.input.via', // computer->phone {via: 'adb'|'phone'}: the input choice changed here (phone.input carries the phone's)
      PHONE_WAKE: 'phone.wake', // computer->phone: screen on and ask for the unlock (on the phone), e.g. to open an app from a notification clicked here
      PHONE_AWAKE: 'phone.awake', // phone->computer {unlocked, waiting?}: unlocked (now, or once the person unlocked it); waiting = it's asking for the unlock
      PHONE_MIRROR: 'phone.mirror', // phone->computer {open}: asked on the phone (its Screen page), its screen in a window on the computer (open, or brought to the front), or open false: the phone's windows there closed
      PHONE_CAMERA: 'phone.camera', // phone->computer {open, facing?}: asked on the phone (its Camera page), its camera running on the computer (the Camera tab's picture and the virtual camera), facing 'back' | 'front'; open false: stopped. The computer says how it's going in adb.bridge's camera
      PHONE_SOUND_WANT: 'phone.sound.want', // computer->phone {on}: its sound here without wireless debugging (playback capture, Start on the phone), while adb can't carry it
      PHONE_SOUND: 'phone.sound', // phone->computer {codec: 'opus'|'pcm', p: [base64]}: 20 ms each (Opus packets, or 48 kHz stereo s16le)
      PHONE_SOUND_STATE: 'phone.sound.state', // phone->computer {on, waiting (for Start on the phone), error, codec}
      PHONE_MIC_WANT: 'phone.mic.want', // computer->phone {on}: its microphone here (an iPhone's app captures it; Android's goes through adb)
      PHONE_MIC: 'phone.mic', // phone->computer {codec: 'pcm', p: [base64]}: 48 kHz stereo s16le, 20 ms each
      PHONE_MIC_STATE: 'phone.mic.state', // phone->computer {on, error}
      // The phone's screen without wireless debugging (shared/nativescreen.js, Mirror.kt): the phone
      // captures it itself (one Start on the phone for the screen and its sound) and sends H.264 over
      // HTTPS to the session's port (POST /twindesk/mirror, header x-twindesk-mirror: key), in
      // scrcpy's 12-byte packets. Only to a phone whose phone.info caps has 'mirror.native'.
      PHONE_MIRROR_WANT: 'phone.mirror.want', // computer->phone {on, key (a secret for the stream), maxSize, bitrate (b/s), fps} | {on, sync: true} (a keyframe now)
      PHONE_MIRROR_STATE: 'phone.mirror.state', // phone->computer {on, waiting (for Start on the phone), error, w, h (the picture), sw, sh (the screen, for phone.in)}
      // A phone's screen through the computer that has it (an iPhone on its cable, an Android phone connected
      // to it), seen and used from another computer through it (shared/phone-relay.js; ios.* from when only
      // an iPhone came this way):
      IOS_SCREEN_WANT: 'ios.screen.want', // viewer->Mac {on, id (its mesh id), key (a secret for the stream), pull (the viewer GETs it)} | {on, key, sync: true}
      IOS_SCREEN_STATE: 'ios.screen.state', // Mac->viewer {key, on, error}
      IOS_INPUT: 'ios.input', // viewer->Mac {id, key, op: touch {a, x, y} | scroll {x, y, hs, vs} | key {code, down} | button {b}} (x, y: 0…1 of the picture)
      // Which iPhone is which on a USB cable, for the whole mesh (shared/ios-links.js):
      IOS_LINKS: 'ios.links', // {links: {UDID: {phone (the app's device id, '' unlinked), name, at}}}
      IOS_CABLE: 'ios.cable', // {phones: [{phone, udid, control (iOS 27: picture and input)}]}: the linked ones on the sender's cable now
      // Apple's developer disk image from a Mac with Xcode, for a computer without it (shared/ios-ddi.js):
      IOS_DDI_WANT: 'ios.ddi.want', // {id}
      IOS_DDI_PART: 'ios.ddi.part', // {id, path (relative), off, data (base64)}
      IOS_DDI_DONE: 'ios.ddi.done', // {id, files: [{path, size}]}
      IOS_DDI_NONE: 'ios.ddi.none', // {id}: no Xcode there, or it failed
      // The Android phones connected to the sender whose screen it serves to the mesh (shared/android-relay.js):
      PHONE_SCREENS: 'phone.screens', // {phones: [{id, name}]}
      // What plays on the phone, for the Overview's media controls (shared/nowplaying.js, NowPlaying.kt):
      PHONE_MEDIA_WANT: 'phone.media.want', // computer->phone {on}: send phone.media (Audio › Media controls on Overview)
      PHONE_MEDIA: 'phone.media', // phone->computer {app, appName, title, artist, album, playing, duration, position, at, speed, next, prev, seek, art?} or {none, why?}; art (a data: URL) only when it changed
      PHONE_MEDIA_CTL: 'phone.media.ctl', // computer->phone {a: 'play'|'pause'|'toggle'|'next'|'prev'|'seek', pos?}
      // …and the other way: what plays on the computer, for the phone's Media page and its media notification (shared/pcnow.js, PcMedia.kt):
      PC_MEDIA_WANT: 'pc.media.want', // phone->computer {on}: send pc.media while on
      PC_MEDIA: 'pc.media', // computer->phone {title, artist, album, app, playing, art?: data: URL ('' none; left out: unchanged)} or {none: true}
      PC_MEDIA_CTL: 'pc.media.ctl', // phone->computer {a: 'play'|'pause'|'toggle'|'next'|'previous'}
      // The phone as the computer's remote (its Remote page: touchpad, keyboard, gamepad), phone->computer.
      // Relative like k.*, applied only while the computer lets the phone control it (Windows for now):
      REMOTE_HELLO: 'remote.hello', // phone->computer: the Remote page opened (the computer answers remote.state)
      REMOTE_STATE: 'remote.state', // computer->phone {allowed, why, pad, text}: whether it takes the remote's input now; pad: as a real gamepad (Remote › Real gamepad); text: it takes remote.text
      REMOTE_MOVE: 'remote.mm', // {dx, dy, smooth?} pixels; smooth: eased out over about a frame on the computer
      REMOTE_DOWN: 'remote.md', // {b}
      REMOTE_UP: 'remote.mu', // {b}
      REMOTE_WHEEL: 'remote.wh', // {dx, dy} pixels
      REMOTE_KEY_DOWN: 'remote.kd', // {code} (KeyboardEvent.code)
      REMOTE_KEY_UP: 'remote.ku', // {code}
      REMOTE_TEXT: 'remote.text', // {text}: characters no key here types (Cyrillic, accents…), typed as they are; only while remote.state says text
      // The Deck (shared/deck.js): a phone's or web device's buttons that this computer runs.
      DECK_OFFER: 'deck.offer', // computer->phone {v}: this computer has the Deck on (none: no Deck page anywhere)
      DECK_HELLO: 'deck.hello', // device->computer {}: it has a Deck
      DECK_LAYOUT: 'deck.layout', // computer->device {layout (no paths), can: [action kinds], caps, mac} | {off: true} (TwinDesk Web, module off)
      DECK_RUN: 'deck.run', // device->computer {id}: a tile
      DECK_DONE: 'deck.done', // computer->device {id, ok, why?}
      DECK_SAVE: 'deck.save', // device->computer {layout}: edited there
      DECK_APPS: 'deck.apps', // device->computer {} / computer->device {apps: [{id, name, icon}]}
      DECK_CLIP: 'deck.clip', // computer->device {text}: Clipboard › Send
      DECK_SET: 'deck.set', // device->computer {id, value 0-1}: a slider tile, while it's dragged; a mixer widget {id, app, value | mute}
      DECK_STATE: 'deck.state', // device->computer {} / computer->device {state: {volume, muted, micVolume, micMuted, outputs, inputs, bt, displays, dark, dnd}}
      DECK_WINS: 'deck.wins', // device->computer {} / computer->device {apps: [{key, name, icon, windows: [{wid, title, display}]}], displays, front}
      DECK_PLACE: 'deck.place', // device->computer {wid, display, zone?: {x, y, w, h} of 12, restore?: a minimized one brought back, op?: close|min|max|full: its own buttons} -> deck.done {id: 'place'}
      DECK_ARRANGE: 'deck.arrange', // device->computer {display, items: [{key, wid?, zone}]}: several apps at once, the ones not running opened -> deck.done {id: 'arrange'}
      REMOTE_LASER: 'remote.laser', // phone->computer {on}: the presentation remote's laser dot here, following the pointer (shared/laser.js)
      REMOTE_RELEASE: 'remote.release', // let go of every key and button the remote holds
      // {b, lx, ly, rx, ry, lt, rt}, only while remote.state says pad: b the buttons (bits 0..13: A B X Y LB RB
      // Back Start L3 R3 Up Down Left Right), the sticks -1..1 (y down), the triggers 0..1; on change, at most every 8 ms
      REMOTE_PAD: 'remote.pad',
      // ReZume (shared/rezume.js, ReZume.kt): what is in use on one side, to go on with on the other.
      // Off until turned on on both sides; offers go only to a side whose rz.policy says on.
      RZ_POLICY: 'rz.policy', // either way, after welcome and on change {on, web, docs, apps, push, windows}: this side takes the other's ReZume offers (and of which kinds; windows: an app's window, computers only)
      // sender->receiver {id, kind: 'web'|'doc'|'app'|'window', title, url? (web), name?, size? (doc), app (bundle id, exe or package), appName, icon? (small PNG data: URL), at, push?}:
      // the tab, document, phone app or app window in use there (kept until another or rz.clear); push: sent on purpose (Send to / Open on computer), opened at once.
      // A window taken is streamed as the Apps tab's are (papp.windows + rtc2 kind 'window', or app.windows from a Mac to a PC); closing it there only stops that.
      RZ_OFFER: 'rz.offer',
      RZ_CLEAR: 'rz.clear', // sender->receiver {id}: nothing to go on with any more
      RZ_TAKE: 'rz.take', // receiver->sender {id}: taken; a doc's file follows as file.offer drop 'rezume', batch 'rz-<id>' (only to a side that asked); a window's are streamed
      // Multi-device: which device ReZume is with, the same on both (shared/rezume-solo.js). {on: true, at}: "I picked you"
      // (at: when, ms); {on: false}: "not any more". Said again as the two connect ({on: true, at, again: true}): the newer pick wins.
      RZ_PARTNER: 'rz.partner',
      RZ_DONE: 'rz.done', // sender->receiver {id, ok, why?}: a doc or window that couldn't be sent (gone, too big, not let through); ok: a window went
      PHONE_SEND: 'phone.send', // computer->phone: clicks the active app's Send button
      PHONE_ACTIVE_APP: 'phone.activeApp', // phone->computer {pkg}: current foreground package
      // Wireless debugging (adb), which the Mac uses for the screen, touch, mouse and keyboard,
      // the clipboard in the background and apps in their own windows (scrcpy):
      ADB_STATE: 'adb.state', // phone->Mac {devOptions, wifi (wireless debugging on), canEnable (WRITE_SECURE_SETTINGS granted), address, full, port (its wireless debugging port from its own mDNS, 0 if not known yet), net (on a Wi-Fi network: wireless debugging can't be on without one)}
      ADB_ENABLE: 'adb.enable', // Mac->phone {on}: switch wireless debugging (needs canEnable)
      ADB_PAIR: 'adb.pair', // phone->computer {code, port?}: the code from "Pair device with pairing code", typed on the phone (port: its pairing port, 0 if unknown)
      ADB_BRIDGE: 'adb.bridge', // computer->phone {state, message}: how the computer's wireless debugging link is doing (off|missing|waitingWifi|needsPair|connecting|ready|error), viewed, camera {on, facing, error, virtual} (its camera running there, for its Camera page), need? (bool: something here uses wireless debugging; false: the phone doesn't switch it on or ask for it; an older computer never says, and the phone does as before)
      // A session through Bluetooth moves onto Wi-Fi for files and screens (shared/netlink.js): one
      // side hosts a network (Wi-Fi Direct group / Windows' legacy access point), the other joins
      // it, and the guest moves the session onto it (hello {resume}, below) without ending it.
      NET_CAPS: 'net.caps', // either {host, join, hotspot, band5?}: what this side can do (host = a network the other joins; band5 false = joins 2.4 GHz only)
      NET_NEED: 'net.need', // either {why: 'files'|'screen'}: please host a network (I can't)
      NET_JOIN: 'net.join', // host->joiner {ssid, pass} | {error}: it's up, join it
      NET_JOINED: 'net.joined', // joiner->host {ok, error?}
      NET_RELEASE: 'net.release', // either {why}: I don't need it any more; {all: true}: Back to Bluetooth, nobody does
      NET_LAN: 'net.lan', // phone->computer {}: its own Wi-Fi network is back while it hosts a link for 'fallback' (General › Network fallback): the link can go
      NET_HOTSPOT: 'net.hotspot', // computer->phone {on}: ask the person to switch the phone's hotspot on (the screen through adb)
      // computer->iPhone or iPad {ads, ble}, as its session starts and when it changes: ads false: this
      // computer's Bluetooth can't advertise (Windows aborts it on some adapters), so the phone advertises
      // instead and the computer links to it (shared/blepipe.js BlePhones, ios BleServe.swift); ble: Bluetooth
      // with phones is on here. Older phones ignore it and keep linking only to a computer that advertises.
      BLE_HOST: 'ble.host',
      // Calls, Messages and Media from a phone (shared/phonehub.js here, Hub.kt on the phone). Each is
      // off until switched on (its page here, or the phone's Overview); while one is off the phone
      // keeps nothing running for it: no listener, no observer, no query.
      HUB_POLICY: 'hub.policy', // computer->phone {calls, messages, media, files, bt}: which are on here (at every session start: it also says the computer has them); bt = call audio here over Bluetooth
      HUB_STATE: 'hub.state', // phone->computer {calls: {perm}, messages: {perm}, media: {perm}, files: {perm}, bt: {name, bonded, le, bonding, forget, allowed, radio}}: perm 'ok'|'partial'|'ask'|'blocked'|'none' (not in this build)
      HUB_ASK: 'hub.ask', // computer->phone {what: 'calls'|'messages'|'media'|'files'|'bt'}: ask the person on the phone for that one's permissions
      HUB_SET: 'hub.set', // phone->computer {what, on}: switched on or off on the phone
      HUB_BT: 'hub.bt', // computer->phone {address, unpair?}: this computer's Bluetooth address (is the phone paired with it?); unpair: forget it (classic and LE). phone->computer {unpair: true}: Forget on the phone, the computer forgets it too. Pairing itself is the person's, in Bluetooth settings
      CALL_STATE: 'call.state', // phone->computer {state: 'idle'|'ringing'|'offhook', number, name, photo?, dir: 'in'|'out', since, held?, silenced?, can?: ['hold'|'dtmf'|'silence']}
      CALL_DO: 'call.do', // computer->phone {a: 'dial'|'answer'|'end'|'mute'|'hold'|'dtmf'|'silence', number?, sim?, on?, key?} (a number with * or # opens the phone's dialer: onPhone in call.done)
      CALL_DONE: 'call.done', // phone->computer {a, ok, error?, onPhone?}
      CALL_LOG: 'call.log', // computer->phone {n} | phone->computer {items: [{number, name, type: 'in'|'out'|'missed'|'rejected'|'blocked', at, dur}]}
      CONTACTS: 'contacts', // computer->phone {q} | phone->computer {q, items: [{name, numbers: [{n, label}]}]}
      SMS_THREADS: 'sms.threads', // computer->phone {n} | phone->computer {items: [{id, addrs, name, snippet, at, unread, out}]}
      SMS_THREAD: 'sms.thread', // computer->phone {id, before?, n} | phone->computer {id, before, items: [{id, body, at, out, from, status, parts?: [{id, type}]}], more}
      SMS_PART: 'sms.part', // computer->phone {id}: an MMS picture | phone->computer {id, data}
      SMS_SEND: 'sms.send', // computer->phone {to, body, ref, sim? (a subscription id from hub.state messages.sims), addrs? (a group: everyone, 2–20), image? (a JPEG data: URL)}: with addrs or image, an MMS (hub.state messages.mms)
      SMS_SENT: 'sms.sent', // phone->computer {ref, ok, error?}
      SMS_NEW: 'sms.new', // phone->computer {thread, summary, msg}: a message arrived or was sent on the phone
      MEDIA_ALBUMS: 'media.albums', // computer->phone {} | phone->computer {items: [{id, name, n, cover}]}: Photos' albums (an older phone never answers)
      MEDIA_LIST: 'media.list', // computer->phone {kind: 'all'|'photos'|'videos'|'screenshots', before?, n} | phone->computer {kind, before, items: [{id, video, at, w, h, size, name, dur, album}], more}
      MEDIA_THUMB: 'media.thumb', // computer->phone {ids}: these next (the ones still waiting are dropped) | phone->computer {id, data}
      MEDIA_VIEW: 'media.view', // computer->phone {id} | phone->computer {id, data}: a big preview
      MEDIA_SAVE: 'media.save', // computer->phone {ids}: send these files here (they come as file.offer, drop 'send')
      MEDIA_DELETE: 'media.delete', // computer->phone {ids}: remove them (phones that say media.remove) | phone->computer {ids: gone, failed, confirm: waiting for Delete tapped on the phone}
      // Photo backup (shared/photo-backup.js; phones that say hub.state media.backup). `key` is the item's
      // own id that stays the same across sessions (Android: as id; iPhone: its library's identifier).
      MEDIA_INDEX: 'media.index', // computer->phone {album, before?, n, videos} | phone->computer {album, before, items: [{key, id, name, at, size, video}], more, next}
      MEDIA_HAS: 'media.has', // computer->phone {keys} | phone->computer {keys: the ones still in the library}
      MEDIA_BACKUP: 'media.backup', // computer->phone {id, batch}: that one file as file.offer drop 'backup' of this batch | phone->computer {batch, ok: false} when it can't be read
      MEDIA_CHANGED: 'media.changed', // phone->computer {}: the library changed (only while hub.policy says backup)
      // Files: the phone's storage, through TwinDesk on it with All files access (no ADB). Paths are
      // relative to the phone's shared storage ('' its top, 'DCIM/Camera'), never '..'.
      FS_LIST: 'fs.list', // computer->phone {path, hidden?} | phone->computer {path, items: [{name, dir, size, at, n? (a folder's items)}], free, total, error?}
      FS_DO: 'fs.do', // computer->phone {a: 'mkdir'|'rename'|'delete', path, name? (mkdir, rename: the new name), paths? (delete), ref}
      FS_DONE: 'fs.done', // phone->computer {ref, ok, error?, path (the folder that changed)}
      FS_SAVE: 'fs.save', // computer->phone {paths}: send these here, folders with what's in them (file.offer, drop 'send')
      FS_EXPECT: 'fs.expect', // computer->phone {batch, path}: the files of this batch (file.offer, drop 'send') go into that folder
      // Shared folders (shared/foldershare.js, FolderShare.kt), on USB, Wi-Fi or Wi-Fi Direct only.
      SHARE_OFFER: 'share.offer', // phone->computer {on, port, secret, name}: its folder over WebDAV at its address, http://<it>:<port>/<secret>/<name>/; sent again when the session moves
      SHARE_HOST: 'share.host', // computer->phone {on, port, token, name}: this computer's folder, http://<computer>:<port>/<token>/<op>?p= (list, stat, file, mkdir, delete, rename)
      SHARE_SET: 'share.set', // phone->computer {serve}: switch the computer's folder for the phone on or off (its setting; share.host says how it is)
      // Internet over USB (#277, shared/tether.js, Tether.kt): the phone's VPN through adb reverse to a
      // relay on the computer. An older phone never sends tether.state, so the computer offers nothing.
      TETHER: 'tether', // computer->phone {on: true, port, token} (its 127.0.0.1:<port> is the computer's relay) | {on: false}
      TETHER_STATE: 'tether.state', // phone->computer {can, state: 'off'|'ask'|'starting'|'on'|'error', why?}: as its session starts and on each change
      // The phone's internet on this computer (#361, shared/phonenet.js, PhoneNet.kt):
      PHONENET: 'phonenet', // computer->phone {on: true, token} | {on: false}
      PHONENET_STATE: 'phonenet.state', // phone->computer {can, state: 'off'|'on'|'error', why, port, addrs: [IPv4], vpn}
      TETHER_SET: 'tether.set', // phone->computer {on}: switched off on the phone (its notification's Stop, or the VPN permission refused)
      // Signing TwinDesk for iPhone with the person's own Apple ID (shared/iossign.js, ios-signer/,
      // Signer.swift): the iPhone keeps the signing state, the computer's helper does the work.
      SIGN_STATE: 'sign.state', // iPhone->computer {signedIn, email, until (ms: its session's end), auto}
      SIGN_INFO: 'sign.info', // computer->iPhone {available, anyIpa, anisette, keep, days, busy, apps: [{bundleId, name, version, team, teamName, expires (s), twindesk, cached (its IPA is kept on the computer)}]}
      SIGN_START: 'sign.start', // iPhone->computer {ipa?: {path (as file.done gave it), size} | app?: bundleId (its IPA is kept on the computer)}: a sealed run
      SIGN_KEY: 'sign.key', // computer->iPhone {pub}: the helper's key for this run
      SIGN_BOX: 'sign.box', // iPhone->computer {pub?, box}: its key and sealed request, then its sealed answers
      SIGN_EV: 'sign.ev', // computer->iPhone {ev: 'step'|'progress'|'need2fa'|'needcert'|'state'|'done'|'error', …}; state's box is sealed for it
      SIGN_WANT: 'sign.want', // computer->iPhone {now?, app?: bundleId}: TwinDesk there runs out soon (now: Refresh was clicked here)
      SIGN_KEEP: 'sign.keep', // either way {state}: the signing state, for the other side to keep (the computer only with Keep a copy on)
      SIGN_STOP: 'sign.stop', // iPhone->computer: stop the run
      SIGN_SET: 'sign.set', // iPhone->computer {on}: App refresh switched there; the computer's TwinDesk iPhone follows (and sign.info {on, switched} the other way)
      // Resume: `welcome` carries {resume: key}; the guest opens a second socket (another path to the
      // host, e.g. the network once both are on one) with hello {..., resume: key} and gets welcome
      // {resumed: true}: from then on both sides send on it, and the first socket stays as the
      // fallback (the session ends only when both are gone).
    },

    // Bluetooth LE, when the two aren't on one network (shared/blepipe.js): the host advertises this
    // GATT service; a guest reads INFO (the host's beacon JSON), writes CTRL ({op: 'hello', id, name,
    // os} | {op: 'open'} | {op: 'close'}; the host notifies {op: 'invite'} | {op: 'closed'}) and
    // pipes the session's bytes: guest writes UP, host notifies DOWN. The session (TLS, pinned
    // certificate, token) runs through that pipe unchanged, the host's side from 127.0.0.1.
    BLE: {
      SERVICE: 'b7f30001-2c4e-4d1a-9a57-3e8c2f6d0a91',
      INFO: 'b7f30002-2c4e-4d1a-9a57-3e8c2f6d0a91',
      CTRL: 'b7f30003-2c4e-4d1a-9a57-3e8c2f6d0a91',
      UP: 'b7f30004-2c4e-4d1a-9a57-3e8c2f6d0a91',
      DOWN: 'b7f30005-2c4e-4d1a-9a57-3e8c2f6d0a91',
      // A phone advertises this one with the same characteristics (its GATT server; the session is
      // still ours): a PC's Bluetooth often can't advertise reliably. The PC connects, says hello,
      // and opens a pipe when it wants the session or the phone asks (CTRL {op: 'want'}).
      PHONE_SERVICE: 'b7f30006-2c4e-4d1a-9a57-3e8c2f6d0a91',
    },

    // Error codes (field `code` of an `error` message)
    E: {
      VERSION_MISMATCH: 'version_mismatch',
      BAD_TOKEN: 'bad_token',
      PAIR_REFUSED: 'pair_refused',
      PAIR_TIMEOUT: 'pair_timeout',
      BUSY: 'busy',
      REPLACED: 'replaced',
      RELEASED: 'released', // the Mac let the phone go (Disconnect): don't resume on your own
      ASLEEP: 'asleep', // the host went to sleep: don't come back on your own (it invites you when it wakes)
      BAD_MESSAGE: 'bad_message',
    },

    // Reasons in kvm.refuse
    REFUSE: { NOT_ALLOWED: 'not_allowed', BUSY: 'busy' },

    // Mouse buttons (field `b`)
    BUTTON: { LEFT: 0, RIGHT: 1, MIDDLE: 2, BACK: 3, FORWARD: 4 },

    // "AB:CD:..." (Node fingerprint256) -> "abcd..."
    normFingerprint(fp) {
      return String(fp || '').replace(/:/g, '').toLowerCase();
    },

    opposite(side) {
      return { left: 'right', right: 'left', top: 'bottom', bottom: 'top' }[side];
    },

    // "Right Option" / "Left Alt" / "Either Command" / "Right Windows key" — the hotkey in words.
    hotkeyName(code, os = 'mac') {
      const m = /^(Alt|Control|Shift|Meta)(Left|Right)?$/.exec(code || '') || [0, 'Alt', 'Right'];
      const key = (os === 'mac' ? { Alt: 'Option', Control: 'Control', Shift: 'Shift', Meta: 'Command' }
        : { Alt: 'Alt', Control: 'Ctrl', Shift: 'Shift', Meta: 'Windows key' })[m[1]];
      return m[2] ? `${m[2]} ${key}` : `${key} (either side)`;
    },

    // Ctrl/Cmd swapping only between different OSes (Mac <-> PC/Linux); same-OS pairs never swap.
    keySwapNeeded(myOs, peerOs) {
      return (myOs === 'mac') !== ((peerOs || (myOs === 'mac' ? 'win' : 'mac')) === 'mac');
    },

    // Role swap: an app in its non-native role (a Mac as guest, a PC
    // as host) passes every message it sends AND every message it receives through swapRole, so
    // its feature code keeps speaking its native role. Returns the messages to use instead (0–2).
    // `st` is one object per session and direction: newRoleSwapState().
    ROLE_SWAP: {
      'rtc.offer': 'rtc2.offer', 'rtc2.offer': 'rtc.offer',
      'rtc.answer': 'rtc2.answer', 'rtc2.answer': 'rtc.answer',
      'rtc.ice': 'rtc2.ice', 'rtc2.ice': 'rtc.ice',
      'stream.stop': 'rtc2.stop', 'rtc2.stop': 'stream.stop',
    },
    newRoleSwapState(peerName) {
      return { audio: false, name: peerName || '', width: 0, height: 0 };
    },
    swapRole(msg, st) {
      if (!msg || typeof msg.t !== 'string') return [msg];
      if (msg.win || msg.kind === 'window') return [msg]; // app-window streams keep their rtc2 names
      if (msg.t === 'stream.info') { // folded into the rtc2.offer's kind
        st.audio = !!msg.audio;
        st.width = msg.width | 0;
        st.height = msg.height | 0;
        return [];
      }
      if (msg.t.startsWith('audio.') && (msg.dir === 'm2w' || msg.dir === 'w2m')) {
        return [{ ...msg, dir: msg.dir === 'm2w' ? 'w2m' : 'm2w' }];
      }
      const t = P.ROLE_SWAP[msg.t];
      if (!t) return [msg];
      if (msg.t === 'rtc.offer') return [{ ...msg, t, kind: st.audio ? 'screen+audio' : 'screen' }];
      if (msg.t === 'rtc2.offer') {
        const { kind, ...rest } = msg;
        const audio = kind === 'screen+audio';
        return [
          { t: 'stream.info', name: st.name, width: msg.width | 0, height: msg.height | 0, audio },
          { ...rest, t },
        ];
      }
      return [{ ...msg, t }];
    },

    // Keys travel as physical DOM KeyboardEvent.code names; "Meta" is Command on the Mac and
    // the Windows key on the PC. The RECEIVER applies this swap to every key that came from
    // the other platform, so Cmd+C on the Mac arrives as Ctrl+C on the PC and the reverse
    // (shortcuts keep their meaning). Alt stays Alt (= Option).
    mapKeyFromOtherPlatform(code) {
      const swap = {
        ControlLeft: 'MetaLeft',
        ControlRight: 'MetaRight',
        MetaLeft: 'ControlLeft',
        MetaRight: 'ControlRight',
      };
      return swap[code] || code;
    },

    // A stylus's state on in.mm/md/mu (android viewer.js), checked: {p pressure 0–1, tx/ty tilt
    // degrees −90…90, tw twist degrees 0–359, c the tip or the eraser touches, er the eraser end,
    // bar the side button held, out it left the screen's range}; null when there is none.
    touchesOf(v) {
      if (!Array.isArray(v) || v.length > 10) return null;
      const out = [], seen = new Set();
      for (const c of v) {
        if (!Array.isArray(c) || !Number.isInteger(c[0]) || c[0] < 0 || c[0] > 9 || seen.has(c[0])) return null;
        const x = Number(c[1]), y = Number(c[2]);
        if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
        seen.add(c[0]);
        out.push([c[0], Math.min(1, Math.max(0, x)), Math.min(1, Math.max(0, y))]);
      }
      return out;
    },

    // A stroke's earlier samples on a pen's in.mm (`pts`, android viewer.js): [[x, y, p, tx, ty], …]
    // normalized x/y, pressure 0–1, tilt degrees; as [{x, y, pen}] with the rest of `pen` (P.penOf's),
    // in order, before the message's own x, y. At most 32; [] when there are none or they don't check.
    penPoints(v, pen) {
      if (!Array.isArray(v) || !pen || !pen.c || v.length > 32) return [];
      const n = (x, lo, hi) => (typeof x === 'number' && Number.isFinite(x) ? Math.min(hi, Math.max(lo, x)) : null);
      const out = [];
      for (const a of v) {
        if (!Array.isArray(a)) return [];
        const x = n(a[0], 0, 1), y = n(a[1], 0, 1);
        if (x === null || y === null) return [];
        out.push({ x, y, pen: { ...pen, p: n(a[2], 0, 1) ?? pen.p, tx: n(a[3], -90, 90) ?? pen.tx, ty: n(a[4], -90, 90) ?? pen.ty } });
      }
      return out;
    },

    penOf(v) {
      if (!v || typeof v !== 'object') return null;
      const n = (x, lo, hi) => (typeof x === 'number' && Number.isFinite(x) ? Math.min(hi, Math.max(lo, x)) : 0);
      const out = v.out === true;
      const c = v.c === true && !out;
      return {
        p: c ? n(v.p, 0, 1) : 0,
        tx: n(v.tx, -90, 90), ty: n(v.ty, -90, 90), tw: ((n(v.tw, -720, 720) % 360) + 360) % 360,
        c, er: v.er === true, bar: v.bar === true && !out, out,
      };
    },
  };

  const nodeCrypto =
    typeof module !== 'undefined' && module.exports && typeof require === 'function'
      ? require('crypto')
      : null;

  if (nodeCrypto) {
    P.randomHex = (bytes) => nodeCrypto.randomBytes(bytes).toString('hex');

    P.sha256Hex = (data) => nodeCrypto.createHash('sha256').update(data).digest('hex');

    // Pairing commit for the Windows nonce: sha256(nonce bytes), hex.
    P.commitOf = (nonceHex) => P.sha256Hex(Buffer.from(nonceHex, 'hex'));

    // 6-digit code both sides show:
    // sha256(SAS_LABEL || fp bytes || nw bytes || nm bytes), first 4 bytes as uint32 BE, mod 1e6.
    P.sasCode = (fp, nwHex, nmHex) => {
      const h = nodeCrypto
        .createHash('sha256')
        .update(Buffer.from(P.SAS_LABEL, 'utf8'))
        .update(Buffer.from(P.normFingerprint(fp), 'hex'))
        .update(Buffer.from(nwHex, 'hex'))
        .update(Buffer.from(nmHex, 'hex'))
        .digest();
      return String(h.readUInt32BE(0) % 1000000).padStart(6, '0');
    };

    // Constant-time check of a token against a stored sha256 hex hash.
    P.tokenMatches = (token, hashHex) => {
      if (typeof token !== 'string' || typeof hashHex !== 'string') return false;
      const a = Buffer.from(P.sha256Hex(token), 'hex');
      const b = Buffer.from(hashHex, 'hex');
      return a.length === b.length && nodeCrypto.timingSafeEqual(a, b);
    };

    // Clipboard text that may be sent (UTF-8 size limit).
    P.clipAllowed = (text) =>
      typeof text === 'string' && Buffer.byteLength(text, 'utf8') <= P.CLIP_MAX_BYTES;
  }

  // Dev: TWINDESK_PING_MS pings the session more often, for finer RTT numbers
  // in the log's [link] line. Only the ping interval changes; the silence limits stay.
  if (typeof process !== 'undefined' && process.env && Number(process.env.TWINDESK_PING_MS) >= 50) P.PING_MS = Math.min(P.PING_MS, Number(process.env.TWINDESK_PING_MS));

  // A phone holds the session the same way whichever it is (it connects when asked, takes over from a
  // computer, gets the grace to resume). Android's extras (adb, scrcpy, its hub) check OS.ANDROID itself.
  // Voice typing refused: the Keyboard switch is off here (remote.state voiceWhy).
  P.KEYBOARD_OFF = 'Keyboard is off on this computer: turn it on in TwinDesk’s Keyboard page there';
  P.isPhoneOs = (os) => os === P.OS.ANDROID || os === P.OS.IOS;

  if (typeof module !== 'undefined' && module.exports) module.exports = P;
  else root.MacShareProtocol = P;
})(typeof self !== 'undefined' ? self : this);