Docs· Build with it

Lifo Desktop: windows, apps and the `desktop` command

View as Markdown

Lifo Desktop is a macOS-like desktop that runs in a browser tab (apps/desktop in the repo): Finder, Examples, Terminal, Code, Browser, Firefox, TextEdit, Activity Monitor and System Settings, all on one Lifo box. Everything it can do to windows and apps goes through one API, which you can reach three ways:

  • From a shell: the desktop command, in every Terminal tab and in box.commands.run(). Text for people, --json for scripts and agents.
  • From the page: window.lifo.desktop, for a host page on the same origin, a test, or an agent driving the browser (Playwright, a browser extension).
  • From an app: ctx.desktop, the same object, in the AppContext every app gets.
bash
desktop open terminal ~/Projects
desktop open firefox https://example.com
desktop snap firefox left && desktop snap terminal right
desktop windows
text
ID  APP       STATE    X    Y   SIZE     TITLE
w3  terminal  focused  700  28  700x788  user@lifo: ~/Projects
w4  firefox   -        0    28  700x788  Example Domain
w1  finder    -        210  117 860x520  user

Examples

The Examples app (second in the Dock, and open when the desktop starts until you turn that off with its checkbox or in System Settings > Login Items) has the playground's example projects as cards: React + Vite, React + TypeScript, Express, Postgres (PGlite), a Supabase todo app and Lifo News on tinbase, Expo, Expo Router and Expo + Supabase, plus Next.js and TanStack Start where the playground has their templates. Running one:

  1. writes its files into ~/Examples/<id> (files you already edited there are kept; Start Over in the card's menu, or --fresh, writes them all again),
  2. opens Code on its main file, top left, and a Terminal in its folder, bottom left, which types its commands (npm install && npm run dev, for example),
  3. when its server listens and answers, opens the Browser on it in the right half.

Examples you'd edit run their dev servers, so a save in Code hot-reloads the page: Lifo News runs npm run dev (Vite, proxying /rest/v1 and /auth/v1 to tinbase) rather than npm start, its production server, which bundles src/ once when it starts.

On a small screen Code is skipped and the Terminal takes the left half. An example that only prints (PGlite) gets the Terminal on the left and Code on the right. Running an example that is already running brings its windows forward; closing its Terminal stops it. If its usual port is taken (Vite moves to 5174), the Browser follows the server to its new port.

bash
desktop examples                       # the list, with each one's port and state
desktop examples open express          # run it (the same code path as the app)
desktop examples open vite-react --wait --json   # return once the Browser is open

The examples are the playground's templates (apps/playground/src/data/templates/*.ts), loaded with import.meta.glob, not copies: apps/desktop/src/examples/registry.ts adds what a template doesn't say (the command, the port, the file to open), and an example whose template file isn't in the checkout is hidden.

Code

Code is a simple editor: a file tree of the project on the left, files in tabs on the right, in Monaco (the editor inside VS Code) with syntax colouring for JavaScript, TypeScript, CSS, HTML, JSON, Markdown, Python, shell, YAML and more. Only Monaco's core and its colourisers load, the first time Code opens; there are no language services, so no IntelliSense or type errors.

  • ⌘S (or Ctrl+S) saves; an edited tab shows a dot, and closing asks to save.
  • Code files (.js, .ts, .jsx, .json, .css, .py, …) open in Code from Finder, the desktop and desktop open server.js; TextEdit stays in Open With.
  • The tree shows the file's project: the nearest folder up with a package.json or .git. Right-click for new files and folders, rename, Show in Finder, Open in Terminal, Trash.
  • A file that changes on disk (a Terminal, a formatter) reloads when you haven't edited it.

Activity Monitor

Activity Monitor opens on Apps: every running app with its windows, frontmost first, each with its title, id (w3), state and size. It follows the desktop's window events, so a window shows up as soon as it opens. Processes, Servers and Memory are the box's side, and desktop open activity processes opens a view directly.

As on a Mac, the toolbar's Stop (the octagon) and Inspect (the ⓘ) act on the selected row: Stop quits an app, closes a window or ends a process, after asking (Quit, or Force Quit, which skips an app's "save changes?"), and Inspect shows its details (an app's package, bundle, file types, URL schemes and commands; a process's command, folder and parent). Click a row to select it, or use the arrow keys; double-click or Enter brings an app or window to the front, inspects a process, or opens a server in Browser; right-click for Show, Quit, Force Quit and Inspect; Delete stops, ⌘I inspects.

Selecting icons

Press on an empty part of the desktop and drag: a selection rectangle follows the pointer and selects the icons it touches as it grows and shrinks. Hold Shift to add to the selection, ⌘ (or Ctrl) to toggle; a click on empty space clears it, Escape while dragging puts the previous selection back. It works with a mouse, a pen or a finger. The selected icons then act together: Enter (or ⌘↓) opens them, ⌘⌫ or Delete moves them to the Trash, dragging one drags them all, and ⌘A (Ctrl+A) selects every icon. Finder's icon and list views select the same way.

Login items and reopened windows

Like a Mac, the desktop reopens the windows you left open: a reload brings each one back where it was, maximized or minimized as it was, in the same order and with the same window in front, and showing what it showed (Finder's folder, a Terminal's tabs and directories, Code's project and files, the Browser's page). System Settings > Login Items > Reopen windows turns that off.

Login items are the apps that open when there's nothing to reopen: the first time the desktop starts, or with Reopen windows off. Finder and Examples are login items by default; System Settings > Login Items turns any app on or off. An app you switched on there also opens next to reopened windows, when it has none of its own. From code: desktop.apps.setLaunchAtStartup('terminal', true), and AppInfo.launchAtStartup says whether an app opens at startup. Apps open in the order they're registered, so the last one is in front.

Windows and targets

Every window has an id, w1, w2, … in the order windows open. An id is never reused while the page lives, so a script can keep one. Wherever a window is expected you can also write:

TargetMeans
w3, or just 3that window
focusedthe focused window
an app id, like terminalthat app's frontmost window

Coordinates are CSS pixels in the desktop page, with (0, 0) at its top-left corner. The menu bar takes the top 28 pixels and the Dock the bottom, so windows live in the work area between them (desktop info prints it). Moves and resizes are kept sensible: a window stays at least its app's minimum size, below the menu bar, and with at least 80 pixels of its title bar on screen. On phones and narrow windows (compact mode) every window fills the work area and can't be moved.

The desktop command

CommandWhat it does
desktop apps [--all]Apps you can open, with where each comes from (built in, installed package and version, or this session). --all adds hidden ones (About This Box, Panel).
desktop open <app|path|url> [arg]Open an app, with an optional argument; a file or folder; or a URL.
desktop windows [--app <id>]Open windows, frontmost first. Alias ls.
desktop focus <win>Bring a window to the front (un-minimizing it).
desktop close <win> [--force]Close a window. Without --force, an app with unsaved changes can keep it open.
desktop minimize <win>Minimize into the Dock.
desktop maximize <win>Fill the work area.
desktop restore <win>Un-minimize a minimized window, or un-maximize a maximized one.
desktop move <win> <x> <y>Move the window's top-left corner. Negative numbers work.
desktop resize <win> <w> <h>Resize (or desktop resize <win> 800x600).
desktop bounds <win> <x> <y> <w> <h>Move and resize at once.
desktop snap <win> <where>left, right, top, bottom, top-left, top-right, bottom-left, bottom-right, center or full.
desktop title <win> <text>Set a window's title.
desktop quit <app> [--force]Close all of an app's windows.
desktop infoScreen size, work area, theme, focused window.
desktop notify [--title <t>] [--timeout <s>] <text>Show a notification. --timeout 0 keeps it until it's closed.
desktop dockApps pinned to the Dock, in order.
desktop dock pin <app> [position] / unpin <app>Change the Dock for this session.
desktop install <npm-package|folder>Install an app package (see Build a desktop app).
desktop uninstall <app>Remove an installed app, or one you registered.
desktop register <id> --url <url> | --html-file <file>Add an app for this session (see below).
desktop unregister <id>Remove an app you registered.
desktop events [--json] [kind...]Print desktop events as they happen until Ctrl+C.
desktop examplesThe example projects, with their ports and whether they're running.
desktop examples open <id> [--fresh] [--wait]Run one (see Examples). --wait returns once the Browser is open.
desktop snapshot save [file] [--full]Save the box with the desktop in it as a .tar.gz in the box (default lifo-desktop-<time>.tar.gz here). --full keeps node_modules and .cache. See Snapshots.
desktop snapshot restore <file> [--force]Bring the desktop back to a snapshot. --force closes windows without asking about unsaved changes.

desktop open decides what you meant in this order: an app id or name (terminal, TextEdit); a path (/…, ~/…, ./…, or a name that exists in the current directory), opened like Finder would (folders in Finder, files by type); a server in the box (localhost:3000, :5173/app), in Browser; a public URL (https://… or example.com), in Firefox when it can run here and in Browser otherwise. An app's argument is made absolute when it names a file that exists, so desktop open textedit notes.md works from any folder.

AppIts argument
findera folder
terminala folder to start in, or run:<command> to run something
browsera port, localhost:<port>/path, an HTML file, or a URL
firefoxa URL, or words to search
codea file (opened in a tab) or a folder (shown in the tree)
textedita file
examplesan example id, to run it
activitya view: apps, processes, servers, memory
settingsa pane: appearance, wallpaper, dock, keyboard, …

Every command takes --json and then prints JSON: the window for window commands, an array for windows, apps and dock, and one object per line for events. Exit codes: 0 when it worked, 1 when the desktop said no (no such window, the app kept it open), 2 for a usage mistake.

bash
# The id of the window that opened, for later commands
id=$(desktop open terminal --json | grep '"id"' | cut -d'"' -f4)
desktop resize $id 900x600

# Tell me when the build is done
npm run build && desktop notify --title Build "finished" || desktop notify --title Build "failed"

# What the user does with windows, as JSON lines
desktop events window --json
text
{"event":"window:focus","windowId":"w2","appId":"terminal","time":1764412800000}
{"event":"window:move","windowId":"w2","appId":"terminal","x":406,"y":220,"time":1764412801520}

Snapshots: save and restore the whole desktop

The desktop keeps its state in its box, like a Mac keeps yours in ~/Library, so a snapshot of the box is a snapshot of the desktop:

In the boxWhat it holds
~/Library/Preferences/lifo.desktop.jsonSettings: appearance, wallpaper, Dock size and magnification, desktop icons, login items, Reopen windows; each app's last window size and position; apps' own preferences (Finder's icon or list view).
~/Library/Application Support/Lifo Desktop/session.jsonThe open windows, back to front: each one's app, the argument it was opened with, bounds, minimized, maximized (and where it goes back to), which one has focus, and the app's own state. Saved as windows change.
/Applications, /System/ApplicationsInstalled apps, and the system apps' bundles.
everything elseYour files.

A snapshot is the box's tar.gz with a lifo-snapshot.json manifest (working directory, environment, when it was saved), the same format Sandbox.exportSnapshot() writes, so it also restores in Node and the CLI (as files). Folders named node_modules and .cache are left out unless you ask for them: npm install brings them back, they'd make a snapshot many times bigger, and the box doesn't keep node_modules across reloads either. A fresh desktop's snapshot is about 45 KB.

From the menu. Lifo menu > Save Snapshot… downloads lifo-desktop-<time>.tar.gz (Save Everything keeps node_modules and .cache too). Lifo menu > Restore Snapshot… picks one and, once you confirm, brings the desktop back to it.

From a shell.

bash
desktop snapshot save ~/Downloads/before.tar.gz   # saved ~/Downloads/before.tar.gz (44.9 KB, 4 windows)
desktop snapshot save --full                      # with node_modules and caches
desktop snapshot restore ~/Downloads/before.tar.gz

From the page.

js
const desktop = window.lifo.desktop;

// Set the desktop up, then save it.
desktop.apps.launch('terminal', '/home/user/Projects');
desktop.windows.snap('terminal', 'right');
const bytes = await desktop.snapshot.save(); // Uint8Array, a .tar.gz
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/gzip' }));
Object.assign(document.createElement('a'), { href: url, download: 'my-desktop.tar.gz' }).click();

// Later, or in another browser: the same files, settings and windows.
const file = await fetch('/my-desktop.tar.gz').then((r) => r.blob());
const { windows, savedAt } = await desktop.snapshot.restore(file); // a Blob, an ArrayBuffer or bytes
console.log(`back to ${savedAt}:`, windows.map((w) => w.title));

Restoring happens in the page, without a reload. The open windows close first; an app with unsaved changes asks, and if you cancel, nothing is restored (the promise rejects with refused; { force: true } closes them anyway). Then the snapshot's files are written into the box, and the desktop reads its preferences and apps again and reopens the snapshot's windows, which get new ids. A restore adds to the box: files in the snapshot replace the ones at the same paths, files it doesn't have stay. A window of an app the desktop doesn't have (one a host page registers with apps.register()) waits, and opens when that app is registered; waiting lists those apps.

What a snapshot doesn't hold: running processes and servers (a Terminal comes back in its directory, not running what it ran), unsaved edits, terminal scrollback, Firefox's history and cookies, and anything kept outside the box.

From the page: window.lifo.desktop

The desktop puts its API on window.lifo.desktop once it has booted and then fires a lifo:desktop-ready event on window. The methods are synchronous unless they say otherwise, and return plain objects you can serialize.

js
// Playwright, or any script in the page
await page.waitForFunction(() => window.lifo?.desktop);
const windows = await page.evaluate(() => window.lifo.desktop.windows.list());
js
const desktop = window.lifo.desktop;

const term = desktop.apps.launch('terminal', '/home/user/Projects'); // → WindowInfo
desktop.windows.snap(term.id, 'right');
desktop.windows.move('finder', 40, 60);
await desktop.open('https://example.com'); // Firefox, or Browser when Firefox can't run

const off = desktop.on('window:close', ({ windowId, appId }) => console.log('closed', windowId, appId));

desktop.notify({ title: 'Deploy', body: 'Live at https://example.com', timeout: 0, onClick: () => desktop.open('https://example.com') });

A host page on the same origin can reach it through the iframe: frame.contentWindow.lifo.desktop. There is deliberately no postMessage bridge: any page can frame the desktop, and a bridge would let it drive the Terminal. A bridge with an origin allowlist is a possible follow-up.

Reference

ts
interface DesktopAPI {
  version: 1;
  info(): DesktopInfo; // { screen, workArea, compact, theme, focused, windows, apps }

  windows: {
    list(filter?: { appId?: string }): WindowInfo[]; // frontmost first
    get(target): WindowInfo | null;                  // null instead of throwing
    focused(): WindowInfo | null;
    focus(target): WindowInfo;
    move(target, x, y): WindowInfo;
    resize(target, width, height): WindowInfo;
    setBounds(target, { x?, y?, width?, height? }): WindowInfo;
    minimize(target): Promise<WindowInfo>;
    maximize(target): WindowInfo;
    restore(target): WindowInfo;
    snap(target, position): WindowInfo;
    setTitle(target, title): WindowInfo;
    close(target, { force? }?): Promise<boolean>;    // false: the app kept it open
    create({ title, url | html | mount, x?, y?, width?, height? }): WindowInfo;
  };

  apps: {
    list({ all? }?): AppInfo[];
    get(appId): AppInfo | null;
    launch(appId, arg?): WindowInfo;
    register(spec: AppSpec | AppDefinition): AppInfo;
    unregister(appId): Promise<boolean>;
    quit(appId, { force? }?): Promise<boolean>;
    setLaunchAtStartup(appId, on): AppInfo;           // a login item (remembered)
    install(spec): Promise<AppInfo>;                  // an npm package name or a folder in the box
    uninstall(appId): Promise<boolean>;
  };

  open(target, arg?): Promise<WindowInfo>;
  examples: {
    list(): ExampleInfo[];       // id, name, description, folder, command, port, main, run
    get(id): ExampleInfo | null;
    open(id, { fresh?, wait? }?): Promise<ExampleRun>; // { id, folder, state, terminal, browser, code, port, url }
  };
  notify(text | { title?, body?, appId?, timeout?, onClick? }): { id, close() };
  dock: { pinned(): string[]; pin(appId, index?): string[]; unpin(appId): string[] };
  menu: { add({ label, items: [{ label, action?, shortcut?, separator?, disabled? }] }): () => void };
  snapshot: {
    save({ full?, exclude? }?): Promise<Uint8Array>;   // the box as a .tar.gz, with the desktop in it
    restore(data: Uint8Array | ArrayBuffer | Blob, { force? }?): Promise<{ savedAt, windows: WindowInfo[], waiting: string[] }>;
  };
  on(event, handler): () => void;
  events: string[];
}

interface WindowInfo {
  id: string; appId: string; appName: string; title: string;
  x: number; y: number; width: number; height: number;
  focused: boolean; minimized: boolean; maximized: boolean; zIndex: number;
}

interface AppInfo {
  id: string; name: string; extensions: string[];
  singleton: boolean; hidden: boolean; builtin: boolean; pinned: boolean;
  source: 'builtin' | 'installed' | 'session'; package: string | null; version: string | null;
  launchAtStartup: boolean; windows: number;
}

Failures throw a DesktopError with a code: not_found (no such window, app or file), invalid (a bad argument), refused (for example replacing a built-in app) or unavailable. The desktop command prints the message and exits 1, or 2 for invalid.

Events

desktop.on(name, handler) and desktop events take these names. Window events carry windowId and appId.

EventExtra fieldsWhen
window:open, window:closea window opened or closed
window:focusa window came to the front
window:minimize, window:restoreminimized into the Dock, and back
window:maximize, window:unmaximizezoomed to the work area, and back
window:movex, yafter a drag, a snap or an API call (not on every frame)
window:resizewidth, heightafter a resize, a zoom or an API call
window:titletitlethe title changed
desktop:focusno window is focused (the desktop was clicked)
app:launchappId, arg?an app opened a new window
app:register, app:unregisterappIdan app was added or removed
notification:showid, title, body, appId?a notification appeared
notification:click, notification:closeidit was clicked, or went away
example:changeid, state, portan example run started, became ready, stopped, or one of its windows opened or closed
dock:change, menu:update, settings:change, trash:changethe Dock, menus, settings or Trash changed

Adding apps

apps.register() takes a short AppSpec: an id, a name and one of url, html or mount.

js
// A server running in the box, as an app in the Dock
desktop.apps.register({ id: 'blog', name: 'My Blog', icon: '📝', url: 'localhost:3000', pin: true });

// A page of your own (a sandboxed iframe: its scripts run but can't reach the desktop)
desktop.apps.register({ id: 'hello', name: 'Hello', html: '<h1>Hello from an app</h1>' });

// Your own DOM, with a handle on the window
desktop.apps.register({
  id: 'clock',
  name: 'Clock',
  size: { width: 280, height: 160 },
  mount(el, win) {
    const tick = () => (el.textContent = new Date().toLocaleTimeString());
    const timer = setInterval(tick, 1000);
    tick();
    return () => clearInterval(timer); // runs when the window closes
  },
});
AppSpec field
idlowercase letters, digits, - and _, starting with a letter; not a built-in app's id
nameshown in the Dock, the menu bar and Spotlight
urla page in an iframe. localhost:<port> (or :<port>) is a server in the box. {arg} is replaced with the launch argument.
htmlHTML in a sandboxed iframe
mount(el, win)draw it yourself; win has id, arg, setTitle() and close(). Return a cleanup function.
iconSVG markup, an image URL, or one or two characters (an emoji, initials) on a colored tile. Default: the name's first letter.
title, size, minSize, singleton, hiddenwindow title, sizes, one window at most, not in the Dock
extensionsfile types it opens, like ['.csv']; opening such a file launches it with the path
pinadd it to the Dock

For full control, pass an AppDefinition like the built-in apps (src/types.ts): createInstance(ctx, arg) returns an AppInstance with mount(), unmount(), getTitle() and optional getMenus(), canClose(), onResize() and openArg() (a single-window app was launched again with an argument).

From a shell, desktop register does the same with a URL or an HTML file:

bash
cd ~/Projects/blog && npx serve -l 3000 &
desktop register blog --url localhost:3000 --name "My Blog" --icon 📝 --size 1000x700 --pin
desktop open blog

Registered apps last until the page reloads. For a window that isn't an app (a report, a preview), desktop.windows.create({ title, html }) opens one directly.

Build a desktop app

Every app on the desktop is a package, the system apps included: a package.json whose lifo.app field is the app's manifest, an icon and one ES module. Install one with desktop install <npm-package|folder> (or desktop.apps.install()) and remove it with desktop uninstall <app>; it lives in the box as /Applications/<Name>.app, next to links to the system apps in /System/Applications, and Finder, the Dock and Spotlight show it at once.

Lifo Desktop apps has the rest: how the desktop loads apps (with a diagram), the manifest, the entry module and what an app gets, commands, file types and URL schemes, building, publishing and installing from npm, a walkthrough with lifo-app-clock, and what an installed app can do.

Firefox

The Firefox app is a real Firefox (Gecko compiled to WebAssembly) in a window, the same engine as the playground's browser agent (An AI agent in the tab). It reaches the real web through a network relay; servers in the box are for the Browser app. There is one Firefox window at most: each one is a whole engine, and they would share a profile. Opening Firefox again with a URL navigates that window.

browser drives it from the Terminal with the same verbs as everywhere else, and opens Firefox when it isn't open:

bash
desktop open firefox https://news.ycombinator.com
browser state | head
browser click new
browser text | head -20

Firefox needs three things. When one is missing, the window says which and how to fix it, and desktop open <url> uses Browser instead.

  • The release at /firefox/ on the desktop's origin. lifo.sh serves it. The desktop's dev server serves it from the website checkout next to the lifo repo (pnpm fetch:firefox there), or from LIFO_FIREFOX_DIR.
  • A cross-origin isolated page, for SharedArrayBuffer. The dev server sends Document-Isolation-Policy: isolate-and-credentialless with the desktop's HTML, which isolates it in Chrome.
  • A network relay. On lifo.sh, log in. The dev server runs one on localhost.

Limits

  • Apps added with apps.register() / desktop register, and Dock changes made through the API, last for the session; installed app packages stay. The Dock's pinned apps aren't in the preferences file, so a snapshot doesn't carry them either.
  • A snapshot holds files, settings and windows, not running processes, unsaved edits or terminal scrollback. Restoring adds to the box rather than replacing it, and a snapshot file saved in the box is part of the next snapshot.
  • The box saves its files to IndexedDB about a second after they change, so the box's copy of a change made just before a reload can be missing; the desktop keeps a copy of its preferences and session in localStorage for that (and to paint its splash screen before the box loads).
  • An app's entry is one ES module: relative imports inside a package aren't resolved, so bundle an app that has more than one file of code. desktop install takes npm packages and folders, not URLs.
  • Coordinates are page pixels, not physical screen pixels, and compact mode ignores moves.
  • window:move and window:resize fire when an interaction ends, not on every frame of a drag.
  • The API is on the page (same origin only). There is no cross-origin bridge.

Edit this page on GitHub