# Lifo Desktop apps

Every app in [Lifo Desktop](https://lifo.sh/docs/build/desktop.md) is a package: Finder, Terminal and Code the same way as
an app you write and install. A desktop app is an npm package whose `package.json` has a
`lifo.app` field, its manifest, next to the `lifo.commands` field [Lifo packages](https://lifo.sh/docs/build/packages.md)
use for terminal commands. With an icon file and one ES module, that's a whole app. It installs
with the box's own npm, lives in the box as a bundle in `/Applications`, and can add commands
to the Terminal too.

```bash
desktop install lifo-app-clock      # from npm
desktop install ~/my-app            # or a folder in the box
desktop open clock                  # the Dock, Spotlight and Finder have it too
desktop uninstall clock
```

## How it fits together

```text diagram=desktop-apps
┌─ Apps ─────────────────────────────────────────────────────────────────────────────────┐
│ System apps: Finder, Terminal, Code, Browser, Firefox, Examples, …                     │
│ Installed apps: lifo-app-clock, yours                                                  │
│ each a package: package.json (lifo.app, lifo.commands), an icon, an entry module       │
└───────────────────────────────────────────┬─────────▲──────────────────────────────────┘
                          ctx.desktop calls │         │ createInstance(ctx), events
┌─ Desktop API ─────────────────────────────▼─────────┴──────────────────────────────────┐
│ window.lifo.desktop  =  ctx.desktop  =  the `desktop` command in every shell           │
│ windows · apps (install, launch, quit) · open · dock · menu · notify · on(event)       │
└───────────────────────────────────────────┬─────────▲──────────────────────────────────┘
            drives windows, the Dock, menus │         │ window and app events
┌─ Desktop shell ───────────────────────────▼─────────┴──────────────────────────────────┐
│ window manager · Dock · menu bar · Spotlight · Finder · Activity Monitor               │
│ app registry: the apps, their icons, file types, URL schemes, login items              │
└───────────────────────────────────────────┬─────────▲──────────────────────────────────┘
                         install, uninstall │         │ registers apps, icons, commands
┌─ App loader (src/core/packages.ts) ───────▼─────────┴──────────────────────────────────┐
│ reads lifo.app from each bundle · imports its entry (blob URL) · registers             │
│ the app and its lifo.commands · watches /Applications and node_modules                 │
└───────────────────────────────────────────┬─────────▲──────────────────────────────────┘
         reads bundles, runs npm install -g │         │ file changes (a watch)
┌─ The box (Lifo) ──────────────────────────▼─────────┴──────────────────────────────────┐
│ files: /System/Applications/*.app  /Applications/*.app  /usr/lib/node_modules          │
│ shell and commands (desktop, browser, clock, …) · npm install -g · lifo install        │
└────────────────────────────────────────────────────────────────────────────────────────┘
```

- **The box** is a Lifo box: its files, its shell and commands, `npm`. Every app is a bundle
  in its filesystem: the apps that come with the desktop in `/System/Applications`, the ones
  you install in `/Applications`.
- **The app loader** (`apps/desktop/src/core/packages.ts`) reads each bundle's manifest from the
  box, imports its entry module from a blob URL (as the Lifo runtime loads a package's
  command), and registers the app and its commands. It watches `/Applications` and
  `/usr/lib/node_modules`, so an app copied in or installed with `npm install -g` in a Terminal
  appears by itself.
- **The desktop shell** is the window manager, the Dock, the menu bar, Spotlight and Finder, over
  a registry of the apps.
- **The desktop API** is one object, reachable three ways: `window.lifo.desktop` in the page,
  `ctx.desktop` in an app, and the `desktop` command in every shell ([reference](https://lifo.sh/docs/build/desktop.md)).
- **Apps** draw their windows and use the API. The system apps are built the same way; their code
  ships inside the desktop, so their entry in the box is a small module that takes it from there
  (nothing is downloaded to start them).

## Build an app

`packages/lifo-app-clock` in the repo is a complete app to copy. Here it is, piece by piece.

### 1. A folder with a manifest

```text
lifo-app-clock/
  package.json    the manifest (lifo.app) and commands (lifo.commands)
  icon.svg        the icon
  app.js          the entry: draws the window
  clock.js        a terminal command
```

```json
{
  "name": "lifo-app-clock",
  "version": "0.1.0",
  "description": "A clock for Lifo Desktop",
  "type": "module",
  "files": ["app.js", "clock.js", "icon.svg"],
  "keywords": ["lifo-app"],
  "lifo": {
    "app": {
      "id": "clock",
      "name": "Clock",
      "icon": "icon.svg",
      "entry": "app.js",
      "window": { "width": 300, "height": 340, "minWidth": 220, "minHeight": 260, "singleton": true },
      "opens": { "schemes": ["clock"] },
      "dock": true
    },
    "commands": { "clock": "clock.js" }
  }
}
```

### 2. The entry

The entry is one ES module. The short form exports `mount`: draw into the window's element and
return a function that cleans up when the window closes.

```js
// app.js
export function mount(el, win, ctx) {
  const time = document.createElement('div');
  time.style.cssText = 'display:grid;place-items:center;height:100%;font:600 28px system-ui';
  el.append(time);
  const tick = () => {
    time.textContent = new Date().toLocaleTimeString();
    win.setTitle(`Clock · ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`);
  };
  tick();
  const timer = setInterval(tick, 1000);
  return () => clearInterval(timer);
}
```

`win` is the window: `win.id`, `win.arg` (what it was opened with: a file, a URL),
`win.setTitle()`, `win.close()`, and what it needs to [come back after a
reload](#saving-a-windows-state) (`win.onSaveState()`, `win.restored`, `win.restoredState`).
`ctx` is [everything an app gets](#what-an-app-gets).

### 3. An icon

An `.svg`, `.png` or `.webp` in the package. Draw it on the 64×64 macOS grid so it sits with the
others in the Dock: a continuous-corner tile about 52 units wide (824/1024 of the canvas), lit
from the top, with a soft shadow. The system apps' icons (`apps/desktop/src/apps/*/icon.svg`)
are good templates; a PNG or WebP gets the same shadow.

### 4. Try it in the box

Put the folder in the box (write it in Code, `git clone` it, or build it there) and install it:

```bash
desktop install ~/lifo-app-clock
desktop open clock
```

It's in the Dock (its manifest says `dock: true`), Spotlight and Finder's Applications at once,
and stays installed after a reload. Change a file and run `desktop install ~/lifo-app-clock`
again to update it.

For quick experiments from the page itself (a script, the browser's console),
`window.lifo.desktop.apps.register({ id, name, mount })` adds an app for the session without
a package.

### 5. A command, a URL scheme

`lifo.commands` maps a command name to a file in the package. It runs like any
[Lifo package's command](https://lifo.sh/docs/build/packages.md#writing-a-lifo-package):

```js
// clock.js: `clock` in any Terminal
export default async function clock(ctx) {
  ctx.stdout.write(`${new Date().toLocaleTimeString()}\n`);
  return 0;
}
```

With `"opens": { "schemes": ["clock"] }`, `desktop open clock://alarm/7` opens Clock with
`win.arg` set to that URL. File types work the same way with `"extensions"`: Finder and
`desktop open notes.clock` open such files in your app.

### 6. Bundle it

The entry is loaded as one module from a blob URL, so relative imports inside the package
don't resolve. Bare imports (`import { h } from 'preact'`) go to a CDN (esm.sh), as for Lifo
package commands. An app with more than one file of code, or TypeScript, or a framework, is
bundled into one ES module first:

```bash
npx esbuild src/app.ts --bundle --format=esm --outfile=app.js
```

```js
// or vite.config.js, library mode
export default {
  build: { lib: { entry: 'src/app.ts', formats: ['es'], fileName: () => 'app.js' }, outDir: '.', emptyOutDir: false },
};
```

esbuild runs inside a Lifo box too, so an app can be written, bundled and installed without
leaving the desktop.

### 7. Publish and install from npm

```bash
npm publish                          # with "keywords": ["lifo-app"]
```

```bash
desktop install lifo-app-clock       # in Lifo Desktop: the box's npm install -g, then its bundle
desktop install lifo-app-clock@0.2.0
```

## The manifest

The `lifo.app` field of `package.json`. Paths are relative to the package folder.

| Field | Type | Default | |
|---|---|---|---|
| `id` | string | required | Lowercase letters, digits, `-` and `_`, starting with a letter, at most 40. Not a system app's id. What `desktop open <id>` and the API use. |
| `name` | string | required | In the Dock, the menu bar, Spotlight, and the bundle's name: `/Applications/<name>.app`. |
| `icon` | string | required | An `.svg`, `.png` or `.webp` file in the package. |
| `entry` | string | required | The ES module that draws the app ([below](#the-entry-module)). |
| `window.width`, `window.height` | number | 760, 500 | The first window's size in CSS pixels (both, or neither). The desktop then remembers the size people give it. |
| `window.minWidth`, `window.minHeight` | number | 320, 200 | The smallest it resizes to (both, or neither). |
| `window.chrome` | `"standard"` \| `"unified"` | `"standard"` | `standard`: the window draws a title bar. `unified`: the app draws its own toolbar (mark it with `data-drag` so it moves the window; buttons in it are excluded) and the traffic lights float over its top-left corner, like Finder. |
| `window.singleton` | boolean | `false` | One window at most: opening it again brings that window forward (and hands it the new argument, see `openArg`). |
| `opens.extensions` | string[] | `[]` | File types it opens, like `[".csv"]`: Finder and `desktop open file.csv` launch it with the path. |
| `opens.schemes` | string[] | `[]` | URL schemes it opens, like `["clock"]`: `desktop open clock://…` launches it with the URL. |
| `launchAtStartup` | boolean | `false` | Open when the desktop starts. People can change it in System Settings > Login Items. |
| `dock` | boolean | `false` | Pin to the Dock when installed. |
| `hidden` | boolean | `false` | Not in the Dock, Spotlight or Applications (About This Box is hidden). |

From the rest of `package.json`: `name` (the package, shown in Activity Monitor's Inspect and
`desktop apps`), `version`, `description`, and `lifo.commands` (command name → file).

## The entry module

The short form, `mount(el, win, ctx)`, suits most apps. The full form is what the system apps
use: `createInstance(ctx, arg)` returns an object the desktop calls through the window's life.

```js
export function createInstance(ctx, arg) {
  let dirty = false;
  return {
    appId: 'notes',
    mount(container, win) {},          // draw (win is the window: id, state, setTitle, …)
    unmount() {},                      // the window closed
    getTitle: () => 'Notes',
    getMenus: () => [{ label: 'File', items: [{ label: 'Save', shortcut: '⌘S', action: () => {} }] }],
    canClose: async () => !dirty,      // false keeps the window open (unsaved changes)
    onResize() {},                     // the window was resized
    focus() {},                        // the window came to the front
    openArg(arg) {},                   // a singleton app was opened again with an argument
    saveState: () => ({ dirty }),      // kept in the session (see below)
    restoreState(state) {},            // reopened from the session, before mount()
  };
}

// Optional, either form: implementations of lifo.commands, instead of files.
export function commands(ctx) {
  return { notes: async (cmd) => (cmd.stdout.write('hi\n'), 0) };
}
```

Menus from `getMenus()` join the standard File, Edit, View, Window and Help menus while the app
is in front. For a menu that stays whatever is in front, use `ctx.desktop.menu.add()`.

## Saving a window's state

The desktop saves its session (every open window, where it is, and what's in it) to a file in
the box as windows change, and reopens it when the desktop starts and when a
[snapshot](https://lifo.sh/docs/build/desktop.md#snapshots-save-and-restore-the-whole-desktop) is restored. Every window
comes back on its own: the desktop launches its app again with the argument the window was
opened with, then puts the window back at its bounds, in its place in the stacking order,
maximized or minimized as it was. An app that does nothing more is reopened as if it was just
launched with that argument.

To bring back more (the folder a window moved on to, the tab that was in front), save it. The
full form has a pair of methods; the desktop calls `saveState()` whenever it saves the session,
and on reopening calls `restoreState(state)` after `createInstance()` and before `mount()`, with
what `saveState()` returned:

```js
export function createInstance(ctx, arg) {
  let folder = arg ?? '/home/user';
  return {
    appId: 'files',
    saveState: () => ({ folder }),                       // any JSON value; undefined saves nothing
    restoreState(state) { if (state?.folder) folder = state.folder; },
    mount(el, win) { /* show folder */ },
    unmount() {},
    getTitle: () => 'Files',
  };
}
```

The short form gets the same through `win`: register what to save with `win.onSaveState(fn)`,
and read it back from `win.restoredState` (`win.restored` is true when the window is being
reopened):

```js
export function mount(el, win) {
  let count = win.restoredState?.count ?? 0;
  const btn = Object.assign(document.createElement('button'), { onclick: () => (btn.textContent = ++count) });
  btn.textContent = count;
  el.append(btn);
  win.onSaveState(() => ({ count }));
}
```

A few rules:

- **Keep it small and quick.** It's JSON in a file the desktop rewrites often. Save where a
  window is (a path, a URL, a tab), not its content: files belong in files.
- **It's called often.** After window events and every two seconds (the file is only written
  when something changed), so don't do work in `saveState()`; return what you have.
- **An argument that acts** (run a command, start a job) would act again when the window is
  reopened with it. Implement `restoreState()` (or check `win.restored`) to know it's a reopening:
  the Terminal ignores a `run:` argument then, and Examples doesn't run the example again.
- **Things move.** A saved path may be gone after a restore; check, and fall back.
- **Nothing to do for older apps.** An app without these is reopened with its argument, as
  before. A `saveState()` that throws, or returns something JSON can't hold, saves nothing for
  that window; a `restoreState()` that throws opens the window without its state.

The system apps save: Finder its folder (and Show Hidden Files), Terminal each tab's directory,
the tab in front and the text size, Code its project, open files and the file in front, Browser
the page (a box server, a URL or an HTML file), Firefox the page, TextEdit its file, Activity
Monitor and System Settings the view or pane they show. None of them saves unsaved text,
terminal scrollback or running processes.

For a preference that belongs to the app rather than a window (a view mode, a sort order), use
`ctx.settings.appPref(appId, key, fallback)` and `ctx.settings.setAppPref(appId, key, value)`:
they're kept in the desktop's preferences file in the box, with the desktop's own settings.

## What an app gets

`ctx` is the same object the system apps get:

| | |
|---|---|
| `ctx.desktop` | The [desktop API](https://lifo.sh/docs/build/desktop.md#from-the-page-windowlifodesktop): `windows` (list, focus, move, resize, snap, close, create), `apps` (list, launch, install, quit), `open(target)`, `notify()`, `dock`, `menu.add()`, `examples`, and `on(event, handler)` for window, app, Dock and notification events. |
| `ctx.box` | The Lifo box behind the whole desktop: `ctx.box.vfs` (its files), `ctx.box.run(line, cwd)` (a shell command, with its output), `ctx.box.processes`, `ctx.box.ports()`, `ctx.box.previewUrl(port)` (a URL that shows a server in the box), `ctx.box.sandbox` (the full [Sandbox API](https://lifo.sh/docs/reference/sandbox.md)). |
| `ctx.files` | Finder's file operations, with their dialogs: new file or folder, rename, move to the Trash. |
| `ctx.settings` | `theme()` (`"dark"` or `"light"`) and `onChange()`; `appPref(appId, key, fallback)` and `setAppPref(appId, key, value)` for the app's own preferences, kept in the box (`~/Library/Preferences/lifo.desktop.json`). |
| `ctx.launch(appId, arg)`, `ctx.open(path)` | Open another app, or a file with the app for it. |

```js
export function mount(el, win, ctx) {
  const off = ctx.desktop.on('window:open', ({ appId }) => console.log('opened', appId));
  el.textContent = ctx.box.vfs.readdir('/home/user').map((e) => e.name).join(', ');
  ctx.desktop.notify({ title: 'Hello', body: `${ctx.box.ports().length} servers running` });
  return off;
}
```

A command (from `lifo.commands`) gets the command context instead (`args`, `stdout`, `vfs`, …),
and reaches the desktop with the `desktop` command or `globalThis.lifo.desktop`.

## The life of an app

- **Install.** `desktop install <npm-package|folder>`, `desktop.apps.install(spec)`,
  `npm install -g` in a Terminal, or copying a bundle into `/Applications`. The bundle is
  `/Applications/<Name>.app`: the package folder. From npm, the box's `npm install -g` fetches
  it into `/usr/lib/node_modules` and the desktop moves it into its bundle, because
  `node_modules` folders are never saved with the box and the app would be gone after a
  reload.
- **Discovery.** At boot the desktop writes the system apps into `/System/Applications` when they
  changed, then loads every bundle there and in `/Applications`; while it runs, it watches
  `/Applications` and `/usr/lib/node_modules`. A package that fails to load is reported in the console
  and the others carry on.
- **Launch.** From the Dock, Spotlight, Finder (double-click its bundle, or a file of a type it
  opens), `desktop open <id> [arg]`, `desktop open <file>`, `desktop open <scheme>://…`, or
  `ctx.launch()`.
- **At startup.** The windows that were open last time are reopened (see
  [Saving a window's state](#saving-a-windows-state)). When there are none to reopen (a first
  start, or Reopen windows switched off), apps with `launchAtStartup`, or switched on in System
  Settings > Login Items, open instead. The person's choice is kept in the box and wins over the
  manifest; an app they switched on also opens next to reopened windows.
- **One window or many.** By default every launch opens a new window (⌥N too), each with its own
  instance. A `singleton` app has one: launching it again brings it forward and calls
  `openArg(arg)` when there's an argument.
- **Quit.** Quit in its menu, the Dock or Activity Monitor (⌥Q, `desktop quit <id>`) closes all
  its windows; an app with no windows left isn't running. `canClose()` can keep a window open for
  unsaved changes; Force Quit skips it.
- **Uninstall.** `desktop uninstall <id>`, Finder's Uninstall on its bundle, moving the bundle to
  the Trash, or `desktop.apps.uninstall(id)`: its windows close, its commands go, its bundle is
  removed. The system apps can't be uninstalled; `/System` is read-only.

## Where apps live

```text
/System/Applications/Finder.app/   a system app: package.json, icon.svg, app.js
/System/Applications/.version      when the system apps were last written
/Applications/Finder.app           a link to /System/Applications/Finder.app
/Applications/Clock.app/           an installed app: the package, as installed
/usr/lib/node_modules/             where npm install -g puts packages (not saved with the box)
~/Library/Preferences/lifo.desktop.json                    the desktop's settings, apps' preferences
~/Library/Application Support/Lifo Desktop/session.json    the open windows and their saved state
```

As on a Mac, `/Applications` lists every app: installed ones are there, system ones are linked
from `/System/Applications`. The desktop rewrites the system apps only when they change (a new
desktop version), so a boot reads them from the box without writing.

## Security and trust

An app runs in the desktop's page with the same access as the desktop and the system apps,
the way a Lifo package's command runs with the box's: it can read and write every file in the
box, run commands, call the whole desktop API, and reach the page (its storage and network).
There is no per-app permission prompt. Install apps you trust, as you would an npm package.

For a page you don't trust, `desktop register --url <url>` or `--html-file <file>` shows it in
a sandboxed iframe for the session: its scripts run, but they can't reach the desktop or the
box. The desktop's box runs in the page; [Security and isolation](https://lifo.sh/docs/understand/security.md)
explains what a box does and doesn't protect.

## Limits

- An entry is one ES module; bundle anything bigger.
- `desktop install` takes npm packages and folders in the box, not URLs.
- Menus are defined in code (`getMenus()`), not in the manifest.
- Installed apps get no sandbox (see above).
