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.
JavaScript androidapple-ecosystemconnectelectronfile-sharingintel-unison-alternativeiosios-windowskde-connect-alternativekvmlinuxmacbookmacosmouse-sharingphone-link-alternativeproductivityscreen-sharingsidecar-alternativesynergy-alternativewindows
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// File Shelf (Mac, Windows and Linux, one-to-one and Multi-device): a small window that holds files.
// Files dropped on it, pasted into it or shaken onto it (a file being dragged, then shaken: the
// helper's shelfShake, shared/shelf-watch.js) stay where they are; the shelf keeps where they are
// while it's open. Its close button lets them go. Each shake opens a new shelf (FileShelves); the tray
// and Files open the last one still open, or a new one.
// Drag them out (one or all), Copy them to the clipboard, Copy to… or Move to… a folder, or drop them on
// a device in the share corner (to its Downloads, as Files › Send). The Recent view (the icon at the
// top right, and the tray menu's File Shelf) lists the last files received.
// Loaded only when opened or when File Sharing › File Shelf is on, and not at all while General ›
// Modules › Files is off. The window only gets opaque ids, never paths; each action checks the file
// is still the one on the shelf (same device and inode) and that the request is from its own frame.
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { randomUUID } = require('node:crypto');
const { BrowserWindow, Menu, dialog, ipcMain, nativeImage, nativeTheme, screen, shell } = require('electron');
const MAC = process.platform === 'darwin';
const WIN = process.platform === 'win32';
const shelves = new Map();
let wired = false;
const RECENT = 8; // the Recent view's length
const HELD = 200; // files on the shelf at most
const W = 280, H = 360;
// The path as given is the real one (no symlink or junction on the way). Windows: case doesn't matter.
const isReal = (file) => { const r = fs.realpathSync.native(file); return WIN ? r.toLowerCase() === file.toLowerCase() : r === file; };
function fileIdentity(file) {
try {
if (typeof file !== 'string' || !path.isAbsolute(file) || !isReal(file)) return null;
const stat = fs.lstatSync(file);
if (!stat.isFile() && !stat.isDirectory()) return null;
return { dev: stat.dev, ino: stat.ino, birthtimeMs: stat.birthtimeMs, size: stat.size, mtime: stat.mtimeMs, folder: stat.isDirectory() };
} catch { return null; }
}
// A received file must be exactly the one that arrived; a held one may have been edited since.
function same(a, b) {
return !!a && !!b && a.dev === b.dev && a.ino === b.ino && a.birthtimeMs === b.birthtimeMs && a.size === b.size && a.mtime === b.mtime && a.folder === b.folder;
}
const sameFile = (a, b) => !!a && !!b && a.dev === b.dev && a.ino === b.ino && a.folder === b.folder;
// A dropped or pasted path, as its real path (a symlink on the way resolved), or null.
function realPath(p) {
try {
if (typeof p !== 'string' || !path.isAbsolute(p)) return null;
return fs.realpathSync.native(p);
} catch { return null; }
}
function owner(event) {
const shelf = shelves.get(event.sender.id);
return shelf && shelf.win && !shelf.win.isDestroyed() && event.sender === shelf.win.webContents &&
event.senderFrame === shelf.win.webContents.mainFrame ? shelf : null;
}
const strings = (list) => (Array.isArray(list) ? list : []).filter((x) => typeof x === 'string').slice(0, HELD);
function wire() {
if (wired) return;
wired = true;
ipcMain.handle('file-shelf:read', (event) => owner(event)?._read() || null);
ipcMain.on('file-shelf:close', (event) => owner(event)?.win.close());
ipcMain.on('file-shelf:view', (event, view) => owner(event)?._setView(view));
ipcMain.on('file-shelf:reveal', (event, id) => {
const item = owner(event)?._item(id);
if (item) shell.showItemInFolder(item.path);
});
ipcMain.on('file-shelf:drag', (event, ids) => owner(event)?._drag(event.sender, typeof ids === 'string' ? [ids] : strings(ids)));
ipcMain.on('file-shelf:add', (event, paths) => owner(event)?._add(strings(paths)));
ipcMain.on('file-shelf:paste', (event) => owner(event)?._paste());
ipcMain.on('file-shelf:remove', (event, ids) => owner(event)?._remove(strings(ids)));
ipcMain.on('file-shelf:clear', (event) => owner(event)?._remove(null));
ipcMain.on('file-shelf:menu', (event, id) => owner(event)?._menu(typeof id === 'string' ? id : ''));
ipcMain.on('file-shelf:portal', (event, m) => {
const shelf = owner(event);
if (shelf && m && typeof m.device === 'string') shelf._portal(m.device, strings(m.ids));
});
ipcMain.on('file-shelf:send', (event, m) => {
const shelf = owner(event);
if (shelf && m && typeof m.device === 'string') shelf._send(m.device, strings(m.ids), strings(m.paths));
});
}
class FileShelf {
// recent() → the received files, newest first ({path, ok}); drop: the Mac's Drop (its .recent and
// 'change'). Without a 'change' event the app calls refresh() when its state changes (cheap while
// the window is closed). file: where the shelf's files are kept (JSON, paths only).
// devices() → [{id, name, os}] connected now; send(paths, id): to that device's Downloads.
// portal(paths, id): the pointer to that device with the files held (devices say portal: true when it can).
// copyFiles(paths): on the clipboard as files (Windows: the helper's clipFiles); clipFiles() → paths.
// onClosed(): its window closed (its files let go).
constructor({ drop, recent, icon, devices, send, portal, copyFiles, clipFiles, onClosed, t = (key) => key }) {
this.drop = drop && typeof drop.on === 'function' ? drop : null;
this.recent = recent || (() => (drop && drop.recent) || []);
this.icon = icon || path.join(__dirname, '..', MAC ? 'mac' : WIN ? 'windows' : 'linux', 'assets', '[email protected]');
this.devices = devices || (() => []);
this.sendTo = send || null;
this.portalTo = portal || null;
this.copyFiles = copyFiles || ((paths) => require('./pastefiles.js').toClipboard(paths));
this.clipFiles = clipFiles || readClipFiles;
this.t = t;
this.win = null;
this.view = 'shelf';
this.items = new Map(); // id → {path, kind, identity, held}
this.held = []; // [{path, identity}], this shelf's own while it's open
this.onClosed = onClosed || (() => {});
this.onChange = () => this._publish();
this.closed = false;
this.lastSent = '';
wire();
}
// ---- the shelf's own files ----
_load() { return this.held; }
_add(paths) {
const held = this._load();
let added = 0;
for (const p of paths) {
const real = realPath(p);
const identity = real && fileIdentity(real);
if (!identity) continue;
const at = held.findIndex((x) => x.path === real);
if (at >= 0) held.splice(at, 1);
held.unshift({ path: real, identity });
added++;
}
if (!added) return;
held.length = Math.min(held.length, HELD);
if (this.view !== 'shelf') this.view = 'shelf';
this._publish();
}
async _paste() {
let paths = [];
try { paths = await this.clipFiles(); } catch { /* nothing usable */ }
this._add(strings(paths));
}
_remove(ids) {
const held = this._load();
const gone = ids ? new Set(ids.map((id) => this.items.get(id)).filter((x) => x && x.held).map((x) => x.path)) : null;
const before = held.length;
this.held = gone ? held.filter((x) => !gone.has(x.path)) : [];
if (this.held.length !== before) this._publish();
}
_setView(view) {
if (view !== 'shelf' && view !== 'recent') return;
this.view = view;
this._publish();
}
// ---- what the window shows ----
_receivedSources() {
const seen = new Set(), found = [];
for (const source of (this.recent() || []).slice(0, 40)) {
if (found.length >= RECENT) break;
if (!source || !source.ok || typeof source.path !== 'string' || seen.has(source.path)) continue;
const identity = fileIdentity(source.path);
if (!identity) continue;
seen.add(source.path);
found.push({ path: source.path, identity, held: false });
}
return found;
}
_heldSources() {
const held = this._load();
const live = held.filter((x) => { const now = fileIdentity(x.path); if (!sameFile(now, x.identity)) return false; x.identity = now; return true; });
if (live.length !== held.length) this.held = live; // moved or deleted elsewhere
return live.map((x) => ({ ...x, held: true }));
}
_snapshot() {
const previous = [...this.items.values()];
this.items = new Map();
const row = (source) => {
const old = previous.find((item) => item.path === source.path && item.held === source.held && (source.held ? sameFile : same)(item.identity, source.identity));
const kind = source.identity.folder ? 'folder' : 'file';
const item = { ...source, kind, id: old?.id || randomUUID() };
this.items.set(item.id, item);
const name = path.basename(source.path);
return { id: item.id, name, kind, size: source.identity.folder ? null : source.identity.size,
...(kind === 'folder' ? { detail: this.t('Folder') } : {}),
extension: source.identity.folder ? '' : path.extname(name).slice(1, 9).toUpperCase() };
};
const items = this.view === 'recent' ? this._receivedSources().map(row) : this._heldSources().map(row);
let devices = [];
try { devices = (this.devices() || []).filter((d) => d && typeof d.id === 'string').slice(0, 10).map((d) => ({ id: d.id, name: String(d.name || ''), os: String(d.os || ''), portal: !!(this.portalTo && d.portal) })); } catch { /* none */ }
return {
view: this.view, items, devices, os: process.platform,
s: {
title: this.t('File Shelf'), recent: this.t('Recently received'), back: this.t('Back to the shelf'),
empty: this.t('Drop files here to keep them at hand'), emptyRecent: this.t('Nothing received'),
hint: this.t('Drag them out, or right-click for Copy and Move'), all: this.t('All {n}', { n: items.length }),
share: this.t('Share'), shareHint: this.t('Hold on a device for more, or let go to send to its Downloads'),
downloads: this.t('Downloads'), portal: this.t('Portal'), devicesBack: this.t('Back'), noDevices: this.t('No device connected'),
reveal: this.t(MAC ? 'Show in Finder' : WIN ? 'Show in Explorer' : 'Show in folder'), close: this.t('Close'),
clear: this.t('Clear'), remove: this.t('Remove from the shelf'),
},
};
}
_item(id) {
if (typeof id !== 'string') return null;
const item = this.items.get(id);
if (!item) return null;
const now = fileIdentity(item.path);
const ok = item.held ? sameFile(item.identity, now) : same(item.identity, now) &&
this._receivedSources().some((source) => source.path === item.path && same(source.identity, item.identity)); // Recent may have been cleared
if (!ok) { this._publish(); return null; }
return item;
}
_paths(ids) { return ids.map((id) => this._item(id)).filter(Boolean).map((item) => item.path); }
_read() {
const state = this._snapshot();
this.lastSent = JSON.stringify(state);
return state;
}
_publish() {
if (!this.win || this.win.isDestroyed()) return;
const state = this._snapshot();
const key = JSON.stringify(state);
if (key === this.lastSent) return;
this.lastSent = key;
this.win.webContents.send('file-shelf:state', state);
}
refresh() { this._publish(); }
// ---- actions ----
_drag(sender, ids) {
const paths = this._paths(ids);
if (!paths.length) return;
const icon = nativeImage.createFromPath(this.icon).resize({ width: 48, height: 48 });
if (icon.isEmpty()) return;
try { sender.startDrag(paths.length > 1 ? { file: paths[0], files: paths, icon } : { file: paths[0], icon }); } catch { /* The native drag may already have ended. */ }
}
_send(device, ids, paths) {
if (!this.sendTo) return;
const list = [...this._paths(ids), ...paths.map(realPath).filter((p) => p && fileIdentity(p))];
if (!list.length) return;
if (!(this.devices() || []).some((d) => d && d.id === device)) return;
this.sendTo([...new Set(list)], device);
}
_portal(device, ids) {
const paths = this._paths(ids);
const d = (this.devices() || []).find((x) => x && x.id === device);
if (!paths.length || !d || !d.portal || !this.portalTo) return;
this.portalTo(paths, device);
}
async _copyTo(item, move) {
const r = await dialog.showOpenDialog(this.win, { title: this.t(move ? 'Move to' : 'Copy to'), properties: ['openDirectory', 'createDirectory'] });
if (r.canceled || !r.filePaths[0] || !this._item(item.id)) return;
const to = uniqueName(path.join(r.filePaths[0], path.basename(item.path)));
try {
if (move) {
try { fs.renameSync(item.path, to); } catch (e) {
if (e.code !== 'EXDEV') throw e;
fs.cpSync(item.path, to, { recursive: true, errorOnExist: true });
fs.rmSync(item.path, { recursive: true, force: true });
}
} else fs.cpSync(item.path, to, { recursive: true, errorOnExist: true });
} catch (e) {
dialog.showMessageBox(this.win, { type: 'warning', message: this.t(move ? 'Couldn’t move {name}' : 'Couldn’t copy {name}', { name: path.basename(item.path) }), detail: e.message });
return;
}
if (item.held) { // the shelf follows the file to where it went
const held = this._load(), at = held.findIndex((x) => x.path === item.path);
if (at >= 0 && move) held[at] = { path: to, identity: fileIdentity(to) };
}
this._publish();
}
_menu(id) {
const item = this._item(id);
if (!item || !this.win) return;
const t = this.t;
Menu.buildFromTemplate([
{ label: t('Copy'), click: () => Promise.resolve().then(() => this.copyFiles([item.path])).catch(() => {}) },
{ label: t('Copy to…'), click: () => this._copyTo(item, false) },
{ label: t('Move to…'), click: () => this._copyTo(item, true) },
{ type: 'separator' },
{ label: t(MAC ? 'Show in Finder' : WIN ? 'Show in Explorer' : 'Show in folder'), click: () => shell.showItemInFolder(item.path) },
...(item.held ? [{ label: t('Remove from the shelf'), click: () => this._remove([id]) }]
: [{ label: t('Keep on the shelf'), click: () => { this.view = 'shelf'; this._add([item.path]); } }]),
]).popup({ window: this.win });
}
// view: 'shelf' or 'recent'; at {x, y}: under the pointer (a shake), shown without taking focus so
// the drag going on carries on into it; nth: the shelves open already (a new one a little lower).
show({ view, at, nth = 0 } = {}) {
if (this.closed) return;
if (view === 'shelf' || view === 'recent') this.view = view;
const area = screen.getDisplayNearestPoint(at || screen.getCursorScreenPoint()).workArea;
const width = Math.min(W, area.width), height = Math.min(H, area.height);
const clamp = (v, lo, hi) => Math.round(Math.max(lo, Math.min(hi, v)));
const bounds = at
? { x: clamp(at.x - width / 2, area.x, area.x + area.width - width), y: clamp(at.y - 60, area.y, area.y + area.height - height), width, height }
: { x: clamp(area.x + area.width - width - 16 - nth * 24, area.x, area.x + area.width - width), y: clamp(area.y + 16 + nth * 24, area.y, area.y + area.height - height), width, height };
const reveal = (win) => { if (at) win.showInactive(); else { win.show(); win.focus(); } };
if (this.win && !this.win.isDestroyed()) {
if (at) this.win.setBounds(bounds);
this._publish();
return reveal(this.win);
}
const win = new BrowserWindow({
...bounds, show: false, title: this.t('File Shelf'), resizable: false, minimizable: false, maximizable: false,
fullscreenable: false, skipTaskbar: true, alwaysOnTop: true, autoHideMenuBar: true,
backgroundColor: nativeTheme?.shouldUseDarkColors === false ? '#f5f5f7' : '#202124', ...(MAC ? { titleBarStyle: 'hiddenInset' } : {}),
webPreferences: { preload: path.join(__dirname, 'preload-file-shelf.js'), contextIsolation: true, nodeIntegration: false, sandbox: true },
});
if (MAC) win.setVisibleOnAllWorkspaces?.(true, { visibleOnFullScreen: true }); // over a full-screen app too
this.win = win;
this.lastSent = '';
const contentsId = win.webContents.id;
shelves.set(contentsId, this);
this.drop?.on('change', this.onChange);
win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
win.webContents.on('will-navigate', event => event.preventDefault());
win.once('ready-to-show', () => { if (this.win === win && !win.isDestroyed()) reveal(win); });
win.once('closed', () => {
shelves.delete(contentsId);
this.drop?.removeListener('change', this.onChange);
if (this.win === win) this.win = null;
this.items.clear();
this.held = []; // closed: its files let go (they stay where they are)
this.view = 'shelf';
this.onClosed();
});
win.loadFile(path.join(__dirname, 'file-shelf.html')).catch(() => { if (!win.isDestroyed()) win.close(); });
}
shutdown() {
this.closed = true;
this.items.clear();
if (this.win && !this.win.isDestroyed()) this.win.destroy();
}
}
// The app's shelves: a shake opens a new one under the pointer; the tray and Files show the last one
// still open, or a new one. Takes FileShelf's options; the same refresh() and shutdown().
class FileShelves {
constructor(opts) {
this.opts = opts;
this.open = [];
this.closed = false;
}
show({ view, at } = {}) {
if (this.closed) return;
const last = this.open[this.open.length - 1];
if (last && !at) return last.show({ view });
const shelf = new FileShelf({ ...this.opts, onClosed: () => { this.open = this.open.filter((x) => x !== shelf); } });
this.open.push(shelf);
shelf.show({ view, at, nth: this.open.length - 1 });
}
refresh() { for (const shelf of this.open) shelf.refresh(); }
shutdown() {
this.closed = true;
for (const shelf of this.open.splice(0)) shelf.shutdown();
}
}
// "name 2.ext" when name.ext is there already.
function uniqueName(p) {
if (!fs.existsSync(p)) return p;
const ext = path.extname(p), base = p.slice(0, p.length - ext.length);
for (let n = 2; n < 1000; n++) if (!fs.existsSync(`${base} ${n}${ext}`)) return `${base} ${n}${ext}`;
return `${base} ${Date.now()}${ext}`;
}
// Files on the clipboard (a file manager's Copy): file URLs, one per line.
async function readClipFiles() {
const { clipboard } = require('electron');
let text = '';
for (const type of ['text/uri-list', 'x-special/gnome-copied-files', 'public.file-url']) {
try { text = typeof clipboard.readBuffer === 'function' ? clipboard.readBuffer(type).toString('utf8') : clipboard.read(type); } catch { text = ''; }
if (text) break;
}
const { fileURLToPath } = require('node:url');
return text.split(/\r?\n/).filter((l) => l.startsWith('file://')).map((l) => { try { return fileURLToPath(l.trim()); } catch { return ''; } }).filter(Boolean);
}
module.exports = { FileShelf, FileShelves, uniqueName };