@shipvo/desktop
v0.0.4
Published
A simulated desktop for Shipvo: windows, menus, file dialogs, tray, notifications and a file system drawn in the browser, with stand-ins for the Electron and Tauri APIs, so AI agents can run and test a desktop app's web build on Windows, macOS and Linux s
Maintainers
Readme
@shipvo/desktop
A simulated desktop for Shipvo. It runs a desktop app's web build inside Windows, macOS and Linux windows in a browser tab, draws the system UI the app asks for (file dialogs, menus, tray, notifications) as real, operable elements, and stands in for the Electron and Tauri v2 APIs, so an AI agent or a test can run the app with no desktop runtime.
npx shipvo run windows # or: mac, linuxUser guide: docs/desktop-sim.md. The command's options: docs/cli.md.
Install
npm i -D @shipvo/desktopshipvo run windows|mac|linux comes with @shipvo/cli (npx shipvo). It needs Node 22.13 or newer. Running an Electron main file needs Node 22.15 or newer. The Vite plugin works with Vite (vite is an optional peer dependency).
Quick start: Electron and Vite
Add the plugin to vite.config.ts. It does nothing in a normal build; it is active only when SHIPVO_DESKTOP=1, which shipvo run sets.
import { defineConfig } from "vite";
import shipvoDesktop from "@shipvo/desktop/vite";
export default defineConfig({ plugins: [shipvoDesktop()] });Run the app on each desktop:
npx shipvo run windows
npx shipvo run mac
npx shipvo run linuxshipvo run builds your web app with npx vite build --outDir .shipvo/desktop-dist --base ./, opens a browser tab with the desktop, and rebuilds when you save. In the app, import ... from "electron" is now the simulated Electron. If package.json names a main file and lists electron, that file runs too, so ipcMain.handle answers ipcRenderer.invoke:
// main.js
import { app, BrowserWindow, ipcMain, dialog } from "electron";
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 900, height: 640 });
win.loadFile("dist/index.html");
});
ipcMain.handle("notes:pick", async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({ properties: ["openFile"] });
return canceled ? null : filePaths[0];
});// renderer
import { ipcRenderer } from "electron";
const path = await ipcRenderer.invoke("notes:pick"); // a file dialog opens on the desktopThe preload file (electron/preload.{ts,js,mjs}, src/preload.{ts,js} or preload.{ts,js}) runs before your app. Pass shipvoDesktop({ preload: "path/to/preload.ts" }) for another place.
With no main process (for example in a test), answer IPC in the page:
import { mockIpc } from "@shipvo/desktop/electron";
mockIpc({ "notes:pick": () => "/Users/me/Documents/todo.txt" });Quick start: Tauri
Use the same plugin. Rust commands cannot run in a browser, so give each one a JavaScript mock in shipvo.desktop.mocks.ts (or .js, in the project root or src/). The plugin runs that file before your app starts.
// shipvo.desktop.mocks.ts
import { registerCommands } from "@shipvo/desktop/tauri/mocks";
registerCommands({
greet: ({ name }) => `Hello, ${name}!`,
read_config: async () => ({ theme: "dark" }),
});import { invoke } from "@tauri-apps/api/core";
await invoke("greet", { name: "Ada" }); // "Hello, Ada!"A command with no mock rejects with this exact message and is logged as invoke.unmocked, so an agent sees what to add:
Command "<name>" has no simulator mock. Add it to shipvo.desktop.mocks.ts.If the project has src-tauri/capabilities/*.json, the plugin hands the permission list to the page and a call without its permission is refused and logged as capability.denied.
The desktop client
Apps written for Shipvo can use the desktop directly. desktop is bound to the window your document lives in.
import { desktop } from "@shipvo/desktop";
desktop.os; // "windows" | "mac" | "linux"
desktop.platform; // "win32" | "darwin" | "linux"
desktop.dark; // true when the desktop is dark
desktop.set({ os: "mac", dark: true }); // re-skins without reloading the appdesktop.set takes os, dark, online and locale. Read-only fields: os, platform, dark, online, locale, app, appRunning. desktop.on("change" | "window" | "log" | "activate" | "window-all-closed", cb) returns an unsubscribe function. desktop.describe() returns a short plain-text summary of windows, menus, dialogs, tray and notifications. hostOf(win?) and windowIdOf(win?) are exported too; hostOf gives the host object itself (with control).
Windows
desktop.window.setTitle("Notes - draft"); // my window
desktop.window.maximize();
desktop.window.getBounds(); // { x, y, width, height } | null
const prefs = desktop.windows.create({ id: "prefs", title: "Preferences", url: "/app/prefs.html", width: 480, height: 360, modal: true, parent: "main" });
desktop.windows.list(); // WindowInfo[]
desktop.windows.focus("main");
// Ask before closing. Return false to veto.
const off = desktop.windows.onCloseRequested(desktop.window.id, () => !hasUnsavedChanges());
await desktop.windows.close("main"); // resolves true when the window closed
desktop.windows.destroy("prefs"); // closes without askingdesktop.window has id, info(), close(), minimize(), maximize(), restore(), focus(), setTitle(), setBounds(), getBounds(), setMenu(). desktop.windows has create, list, get, focus, close, destroy, closeAll, onCloseRequested, workArea, setZoom, getZoom, minimize, maximize, restore, setBounds, setTitle, setMenu, getMenu, frameOf, show, hide, setFullscreen, load. WindowOptions fields: id, title, url, x, y, width, height, minWidth, minHeight, resizable, frameless, modal, parent, show. The first window is main.
Menus
Accelerators use Electron's spelling. CmdOrCtrl is Cmd on macOS and Ctrl on Windows and Linux, and menus show it that way.
desktop.menu.setApplicationMenu([
{ label: "&File", submenu: [
{ label: "Save", accelerator: "CmdOrCtrl+S", click: save },
{ type: "separator" },
{ role: "quit" },
] },
{ role: "editMenu" },
]);
desktop.menu.click(["File", "Save"]); // true when an enabled item ran
const id = await desktop.menu.popup([{ id: "copy", label: "Copy" }], { x: 40, y: 40 }); // the chosen id, or nullAn app that never sets a menu gets the default one (File, Edit, View, Window; on macOS an app menu first). setApplicationMenu(null) removes it. desktop.menu has setApplicationMenu, getApplicationMenu, popup, click, closeAll. Menu item fields: id, label, type (normal, separator, submenu, checkbox, radio), role, accelerator, enabled, checked, visible, submenu, click. A & before a letter in a label is a mnemonic (Alt+letter on Windows and Linux).
Dialogs
File and message dialogs are drawn as role="dialog" elements that a person or an agent operates.
const files = await desktop.dialog.open({
title: "Open note",
filters: [{ name: "Text", extensions: ["txt", "md"] }],
properties: ["openFile", "multiSelections"],
}); // string[] | null
const target = await desktop.dialog.save({ defaultPath: desktop.paths.join(desktop.paths.get("documents"), "note.txt") });
const { response, checked } = await desktop.dialog.message({
type: "question", title: "Close", message: "Discard changes?",
buttons: ["Discard", "Cancel"], defaultId: 1, cancelId: 1,
});open and save also take defaultPath, buttonLabel, showHiddenFiles and windowId. message also takes detail, checkboxLabel and windowId. The file dialogs browse the simulated file system. Button order follows the OS.
File system and paths
The file system is in memory and kept in sessionStorage under shipvo.desktop.fs, so a reload keeps the files. Each OS skin has its own tree. Nothing touches the real machine.
desktop.fs.mkdir(desktop.paths.join(desktop.paths.get("documents"), "notes"), { recursive: true });
desktop.fs.writeFile(target!, "hello"); // string or Uint8Array
desktop.fs.readFile(target!, "utf8"); // string; without an encoding, Uint8Array
desktop.fs.readdir(desktop.paths.get("documents")); // { name, isDirectory }[]
desktop.fs.stat(target!); // { isFile, isDirectory, size, mtimeMs } | null
desktop.fs.exists(target!);
desktop.fs.rename(target!, target! + ".bak");
desktop.fs.rm(target! + ".bak");fs also has mkdir and rm with { recursive }. Errors carry a Node-style code: ENOENT, EEXIST, EISDIR, ENOTDIR, ENOTEMPTY, EPERM, EINVAL. Encodings: utf8, base64, hex, latin1, binary, ascii.
desktop.paths.get(name) takes home, desktop, documents, downloads, appData, userData, temp, exe, and follows the OS:
| | Windows | macOS | Linux |
| --- | --- | --- | --- |
| home | C:\Users\me | /Users/me | /home/me |
| documents | C:\Users\me\Documents | /Users/me/Documents | /home/me/Documents |
| appData | C:\Users\me\AppData\Roaming | /Users/me/Library/Application Support | /home/me/.config |
| temp | C:\Users\me\AppData\Local\Temp | /tmp | /tmp |
Also desktop.paths.sep, join, basename, dirname and extname, which follow the OS (backslashes on Windows).
Clipboard
desktop.clipboard.writeText("copied");
desktop.clipboard.readText(); // "copied"
desktop.clipboard.clear();In app windows, navigator.clipboard.readText() and writeText() use this clipboard too.
Notifications
const id = desktop.notifications.show({ title: "Saved", body: "note.txt", timeoutMs: 5000 });
desktop.notifications.on("click", (n) => console.log("clicked", n.id));
desktop.notifications.list(); // shown now
desktop.notifications.history(); // everything since the last reset
desktop.notifications.click(id); // what a click on the toast does
desktop.notifications.close(id);The toast appears in the corner the OS uses. The page's Notification class shows the same toasts.
Tray
const tray = desktop.tray.create({
tooltip: "Notes", title: "Notes",
menu: [{ label: "Show", click: () => desktop.windows.focus("main") }, { role: "quit" }],
});
desktop.tray.on("click", (e) => console.log(e.type, e.openedMenu));
await desktop.tray.simulate(tray, "right-click"); // what a real pointer does on this OS
desktop.tray.update(tray, { tooltip: "Notes (1 unsaved)" });
desktop.tray.remove(tray);desktop.tray has create, update, remove, click, list, on, simulate, rect. TrayOptions fields: id, tooltip, title, menu, menuOnLeftClick (default: macOS true, Windows and Linux false) and menuOnRightClick (default true). Events: click, right-click, double-click, middle-click, mouse-enter, mouse-leave, mouse-move, as each OS reports them.
Shortcuts
desktop.shortcuts.register("CmdOrCtrl+Shift+N", () => newNote()); // false if invalid or taken
desktop.shortcuts.press("CmdOrCtrl+Shift+N"); // runs the shortcut, or the menu item with that accelerator
desktop.shortcuts.isRegistered("CmdOrCtrl+Shift+N");
desktop.shortcuts.unregister("CmdOrCtrl+Shift+N");
desktop.shortcuts.unregisterAll();Shell
await desktop.shell.openExternal("https://shipvo.dev"); // logged; nothing opens
desktop.shell.showItemInFolder(target!);
await desktop.shell.openPath(target!);
desktop.shell.beep();Theme
desktop.theme.get(); // "light" | "dark"
desktop.theme.set("dark");
const off2 = desktop.theme.on("change", (v) => console.log(v));matchMedia("(prefers-color-scheme: dark)") in app windows follows the desktop theme.
Log
Everything the simulator does is logged and marked simulated: true.
desktop.log(); // [{ t, kind, simulated: true, detail }, ...]
desktop.clearLog();
desktop.record("app.saved", { path: "note.txt" }); // add your own entry
desktop.on("log", (entry) => console.log(entry.kind));Kinds start with window., dialog., menu., fs., clipboard., notification., tray., shortcut., shell., ipc., invoke., capability. or plugin..
Electron stand-ins
@shipvo/desktop/electron is electron in your windows (renderer and preload). Everything below exists with Electron's names.
| Module | What is there |
| --- | --- |
| ipcRenderer | send, invoke, sendSync (returns undefined and logs a warning), on, addListener, once, off, removeListener, removeAllListeners, listenerCount, setMaxListeners, postMessage, sendToHost |
| contextBridge | exposeInMainWorld (sets a frozen copy on window[key]), exposeInIsolatedWorld |
| webFrame | zoom factor and level, insertCSS, removeInsertedCSS, executeJavaScript |
| clipboard | readText, writeText, readHTML, writeHTML, write, clear, availableFormats, has |
| shell | openExternal, showItemInFolder, openPath, beep, trashItem |
| nativeTheme | shouldUseDarkColors, themeSource, on("updated") and the contrast reads |
| webUtils | getPathForFile |
| mockIpc, mockIpcEmit | answer ipcRenderer calls in the page with no main process |
@shipvo/desktop/electron/main is electron in the main process, used by the main host: app, BrowserWindow, ipcMain, dialog (including the *Sync forms), Menu, MenuItem, Tray, Notification, shell, clipboard, nativeTheme, globalShortcut, screen, nativeImage, session, protocol, powerMonitor, autoUpdater.
@shipvo/desktop/main-host exports startMainHost({ main, projectDir, port, token, os, onOutput? }), which runs the main file in a child Node process, and mainPageScript(opts?), the page half the run page includes. The main process may write only under <project>/.shipvo/userData, which is what app.getPath("userData") returns.
Tauri stand-ins
The Vite plugin points these at @shipvo/desktop/tauri/<name>.
| Package | Stand-in |
| --- | --- |
| @tauri-apps/api and @tauri-apps/api/core | core: invoke, convertFileSrc, Channel, Resource, isTauri |
| @tauri-apps/api/event | event: listen, once, emit, emitTo |
| @tauri-apps/api/window, webviewWindow, webview | window, webviewWindow, webview |
| @tauri-apps/api/app, path, menu, tray, dpi, image, mocks | app, path, menu, tray, dpi, image, mocks |
| @tauri-apps/plugin-dialog | open, save, message, ask, confirm |
| @tauri-apps/plugin-fs | text and binary read and write, readDir, mkdir, remove, rename, copyFile, exists, stat, lstat, truncate, size, open, create, watch, BaseDirectory |
| @tauri-apps/plugin-clipboard-manager | writeText, readText, writeHtml, writeImage, readImage, writeSecret, clear |
| @tauri-apps/plugin-notification | isPermissionGranted, requestPermission, sendNotification, onAction and the rest of the plugin's functions |
| @tauri-apps/plugin-shell | open, Command (answered by a shell:<program> mock) |
| @tauri-apps/plugin-os | platform, type, arch, version, family, eol, exeExtension, locale, hostname |
| @tauri-apps/plugin-global-shortcut | register, unregister, unregisterAll, isRegistered |
| @tauri-apps/plugin-store | Store, LazyStore, load, getStore (kept in the simulated file system) |
| @tauri-apps/plugin-opener | openUrl, openPath, revealItemInDir |
| @tauri-apps/plugin-process | exit, relaunch |
| @tauri-apps/plugin-http | fetch (answered by an http:fetch mock) |
| @tauri-apps/plugin-log | error, warn, info, debug, trace, attachConsole, attachLogger |
| @tauri-apps/plugin-window-state | StateFlags, saveWindowState, restoreState, restoreStateCurrent, filename |
| @tauri-apps/plugin-autostart, plugin-cli, plugin-deep-link, plugin-positioner, plugin-updater | stand-ins with the plugin's function names |
| @tauri-apps/plugin-sql, plugin-stronghold, plugin-upload, plugin-websocket | reject with a message naming the call and log plugin.unsupported |
The mocks file (@shipvo/desktop/tauri/mocks) exports registerCommands, clearCommands, hasCommand, mockIPC, mockWindows, clearMocks, setNotificationPermission and simulateOpenUrl.
Write a test
A unit test with control
createDesktopHost from @shipvo/desktop/host makes a desktop on a root element. host.control is the surface for tests: seedFiles(files), setClipboard(text), answerDialog(next), reset(). answerDialog({ response?, paths?, checked? }) pre-answers the next dialog (open, save or message), so a test does not have to click.
import { test } from "node:test";
import assert from "node:assert/strict";
import { createDesktopHost } from "@shipvo/desktop/host";
test("the app opens the file the person picked", async () => {
const host = createDesktopHost({ root, os: "mac" }); // root: an element from your test DOM
host.control.seedFiles({ "~/Documents/todo.txt": "buy bait" });
host.control.answerDialog({ paths: ["/Users/me/Documents/todo.txt"] });
const [picked] = await host.dialog.open({ properties: ["openFile"] });
assert.equal(host.fs.readFile(picked, "utf8"), "buy bait");
assert.ok(host.log().every((entry) => entry.simulated === true));
host.control.reset();
});In seeded paths ~ is the home folder of the current OS. This package's own tests build their host with a small fake DOM: test/core-helpers/make-host.mjs. Run them with pnpm --filter @shipvo/desktop test.
In a real browser
shipvo run windows|mac|linux serves the desktop and an agent channel. A test connects as the driver, reads the screen, and acts with refs: see the agent section of docs/desktop-sim.md. set_desktop seeds files, sets the clipboard and pre-answers a dialog from there.
The package also runs its own app in headless Chromium on all three skins with Playwright and Vitest: packages/desktop/e2e/desktop.e2e.test.mjs and packages/desktop/e2e/tauri.e2e.test.mjs (pnpm --filter @shipvo/desktop test:e2e). Electron main-process behaviour is tested end to end in packages/desktop/test/electron-e2e.test.mjs.
Export paths
| Import | File |
| --- | --- |
| @shipvo/desktop | src/index.ts: desktop, hostOf, windowIdOf, createClient and every type |
| @shipvo/desktop/host | src/host/index.ts: createDesktopHost, defaultChrome |
| @shipvo/desktop/types | src/types.ts |
| @shipvo/desktop/electron | src/electron/index.ts: electron in app windows |
| @shipvo/desktop/electron/main | src/electron/main.ts: electron in the main process |
| @shipvo/desktop/main-host | src/main-host/index.ts: startMainHost, mainPageScript |
| @shipvo/desktop/vite | vite.mjs: shipvoDesktop (default and named), rewriteProcessPlatform, electronRequireToImport, readTauriCapabilities, PLATFORM_EXPR |
| @shipvo/desktop/tauri/<name> | src/tauri/<name>.ts, for example @shipvo/desktop/tauri/mocks |
The source is published as TypeScript. Browser files in it import no Node modules.
License: Apache-2.0.
