# Apps and publishing

An app is a folder of web files in the workspace. When it needs structured data, it binds to approved operations on one or more transactional Collections through `app.publish.json` and calls them over the `dohc-app-channel` `MessagePort`.

## `app.publish.json` format

Place `app.publish.json` inside the app folder. Modern manifests omit `inputs`, `packageMap`, `revision`, and `revisionSha256`, and reference operations by name:

```json
{
  "version": 1,
  "entryPath": "src/App.tsx",
  "dataset": {
    "kind": "dataset",
    "datasetPath": "tracker/dataset.json",
    "operations": ["listExpenses", "createExpense"]
  }
}
```

Rules:

- Always include `"version": 1` and `"entryPath"` (relative to the app folder, no leading `/`).
- `inputs` is optional. When omitted, dohc discovers the app folder's source files automatically. When provided, every path is relative to the app folder and must include `entryPath`.
- `packageMap` is optional and defaults to `{}`.
- `dataset.datasetPath` is relative to the workspace root and ends in `dataset.json`.
- Use either `operations: ["opName", ...]` (recommended) or `operationIds: ["<UUID>", ...]`, never both. Omit `revision` and `revisionSha256` so `prepareLocal`, `prepare`, and `stage` pin the latest approved Collection revision automatically.
- An app can bind up to 16 Collections using `datasets` instead of `dataset`: an object map `"datasets": { "<alias>": { "kind": "dataset", "datasetPath": "...", "operations": [...] } }` (call `backend.invoke` with `dataset: "<alias>"`). Apps with more than one Collection get no live updates on a share link.
- Only one of `dataset`, `datasets`, or `collection` may appear.
- For typed rows, run `dohc dataset types '{"workspaceId":"...","datasetPath":"..."}'`. It writes `.dohc/types/<name>-<datasetId>.d.ts` from the approved revision and returns the exact `path`. Import it with `import type { FieldIds, Row, Operations } from "<relative path>/.dohc/types/<name>-<datasetId>"` and run it again after each approved change. Give a custom `action` a `contract` in `dataset.json` to type it with `Input<"name">` and `Output<"name">`. A contract is `{ "input": type, "output": type }`. A type is `"string"`, `"number"`, `"boolean"`, `"unknown"`, `{ "enum": [...] }`, `{ "array": type }`, `{ "nullable": type }`, or `{ "object": { "key": type }, "optional": ["key"] }`. dohc does not check values against it, so the action still checks its input.
- For public share-link apps, list only `access: "link"` operations. Never include owner-only reads in a public app manifest.
- Don't put the app's icon or title here: `app.publish.json` refuses unknown keys. They go in the app folder's `dohc.json`, as `{ "title": "Signups", "icon": "🎟️" }`, which stays outside the app's approval unless this file lists it among its inputs.

## Built-in app kit and TypeScript/JSX

The closed app compiler bundles `.ts`, `.tsx`, `.js`, `.jsx`, and `.css` with extensionless relative imports and ships a built-in kit without needing `node_modules`:

- `react`, `react-dom`, `react-dom/client`, `react/jsx-runtime`
- `dohc/app` (backend client and hooks), `dohc/ui` (optional themed controls and formatters), `dohc/charts` (optional SVG charts)
- `dohc/icons` (a curated set of Lucide icons, such as `Plus`, `Trash2`, `Receipt`, and `Wallet`; unused icons are left out of the bundle)
- `dohc/money` (`formatCents` and `parseCents` for exact whole-cent amounts) and `dohc/csv` (`parseCsv` and formula-safe `toCsv`)

Other packages, including `lucide-react`, need their files in the app folder and a `packageMap` entry.

### Choosing styles

New apps from `dohc_create_app` start with plain React and `src/styles.css`, without importing `dohc/ui`.

- **Default to app-owned CSS.** Design the layout, palette, typography, and density around the app's job and audience, especially for public share links, full-viewport tools, workbenches, and games.
- **Opt into `dohc/ui` for quick internal utilities.** Use `dohc/ui` and `AppShell` when building a fast workspace dashboard, tracker, or list view that benefits from ready-made accessible controls.
- **Mix selectively when useful.** You can import individual controls such as `Modal` or `DateField` from `dohc/ui` without using `AppShell`. The kit places its `:root` tokens and `html, body` defaults in `@layer dohc-kit`, so unlayered `:root` and `body` rules in your CSS override them regardless of import order. Override `--kit-*` tokens and `color-scheme` in `:root`, adding `@media (prefers-color-scheme: dark)` when your app supports both themes.

## Calling Collection operations (`dohc-app-channel`)

The host delivers one `MessagePort` to the app window on load. Wait for `{ kind: "dohc-app-channel", version: 1 }` and send `backend.invoke` messages on that port:

```js
let channelPort;
const pending = new Map();
const queue = [];

function send(message) {
  return new Promise((resolve, reject) => {
    const id = crypto.randomUUID();
    const frame = { id, ...message };
    pending.set(id, { resolve, reject });
    if (channelPort) channelPort.postMessage(frame);
    else queue.push(frame);
  });
}

window.addEventListener("message", (event) => {
  if (
    channelPort ||
    event.source !== window.parent ||
    event.data?.kind !== "dohc-app-channel" ||
    event.data?.version !== 1 ||
    event.ports.length !== 1
  ) {
    return;
  }
  channelPort = event.ports[0];
  channelPort.onmessage = ({ data }) => {
    const req = pending.get(data?.id);
    if (!req) return;
    pending.delete(data.id);
    if (data.ok) req.resolve(data.value);
    else req.reject(new Error(data.error?.message ?? `Request failed (${data.status})`));
  };
  channelPort.start();
  while (queue.length) channelPort.postMessage(queue.shift());
});

// Single-Collection call (add `dataset: "<alias>"` for multi-Collection apps):
// const { result } = await send({
//   op: "backend.invoke",
//   operation: "listExpenses",
//   input: {},
//   idempotencyKey: crypto.randomUUID(),
// });
```

Other channel operations: `backend.upload` (`name`, `contentType`, `bytes` as a transferred `ArrayBuffer` up to 20 MiB, `idempotencyKey`), `backend.file` (`fileId`, `operation`, `input`; replies `{ file, bytes }` with `bytes` as a transferred `ArrayBuffer`), `backend.attempt` (`operation`, `request`), `host.copy` (`text`, up to 65,536 UTF-8 bytes, user-activated), `host.print` (optional `height`, 1 to 50,000 CSS pixels, user-activated), and for document-Collection share-link apps: `collection.list` and `collection.create`.

## Sandbox constraints (`window.origin === "null"`)

Every app runs in a sandboxed `srcdoc` iframe with an opaque origin (`window.origin === "null"`), without `allow-same-origin` or `allow-modals`:

- Do not read or write `sessionStorage`, `localStorage`, `indexedDB`, or `document.cookie`. They throw `SecurityError` in an opaque origin. Keep UI state in memory and persist data in Collections.
- Do not call `navigator.clipboard.writeText(...)` directly inside the app frame. Chromium logs a Permissions Policy `console.error` even inside `try/catch`, which fails `verifyFrontend`. Import `copyText(text)` from `dohc/app` (or send `host.copy` over `dohc-app-channel`) from a click or key handler.
- Do not call `window.print()` directly inside the app frame. Chromium ignores it without `allow-modals`. Import `print()` from `dohc/app` (or send `host.print` over `dohc-app-channel`) from a click or key handler. When the printable area scrolls inside a fixed-height container, expand it in `@media print` (`height: auto; overflow: visible`) and pass `{ height }` with the container's full scroll height so rows below the viewport are not clipped. For standalone offline exports, generate a Blob download via `allow-downloads`.
- Call `requestFullscreen()` only when `document.fullscreenEnabled` is `true`, from a click or key handler. A share link allows full screen; dohc's own tab and `verifyFrontend` don't, and there it rejects and logs a Permissions Policy `console.error` that fails `verifyFrontend`. Fill the frame with CSS (`height: 100vh`).
- Give an `IntersectionObserver` an explicit `root` (`document` or the scrolling element) when it uses `rootMargin`. Without one, the opaque-origin frame ignores `rootMargin`, and content loads only once it is already visible.

## Verifying an app frontend (`dohc_publish_app` `verifyFrontend`)

`verifyFrontend` works only in a workspace you own; in a workspace you joined, check a Personal app's source with `checkLocal` and its `appRoot` from `personalFolder`. Before publishing or handing an app to a user, verify its compiled frontend inside dohc's real sandboxed document, CSP, and `dohc-app-channel` broker with `{ action: "verifyFrontend", workspaceId, appRoot }` (candidate source) or `{ action: "verifyFrontend", workspaceId, publicationId }` (active local publication, or a workspace-audience app's served bundle; add `memberId` to run as one member's actions). Specify exactly one of `appRoot` or `publicationId`.

- Runs completely offline against a fresh, empty ephemeral Collection database (never reads or mutates live Collection rows, uploaded files, or workspace files).
- Catches manifest/input errors, bundle compile errors, CSP violations (inline scripts, native form submission without `event.preventDefault()`), uncaught page/console errors, broken `dohc-app-channel` handshakes, malformed broker messages, and unapproved operations.
- Optional checks:
  - `expectStartupBackend`: array of `{ op?, operation?, status?, refusalCode? }` expected during startup.
  - `steps`: ordered UI checks (`{ kind: "waitFor", selector, textIncludes? }`, `{ kind: "fill", selector, value }`, `{ kind: "click", selector, expectBackend? }`).
  - `timeoutMs`: `1000`–`30000` (default `10000`).
- Use `dohc_test_app` for quick folder detection and entry presence checks; use `verifyFrontend` to compile and run the frontend end to end against an empty ephemeral Collection.

```json
{
  "request": {
    "action": "verifyFrontend",
    "workspaceId": "<workspaceId>",
    "appRoot": "apps/booking",
    "steps": [
      { "kind": "fill", "selector": "#name", "value": "Ada" },
      { "kind": "fill", "selector": "#seats", "value": "5" },
      {
        "kind": "click",
        "selector": "#submit",
        "expectBackend": { "op": "backend.invoke", "operation": "createBooking", "status": 200 }
      },
      { "kind": "waitFor", "selector": "#status", "textIncludes": "Booked" }
    ]
  }
}
```

## Local approval, staging, and launch (`dohc_publish_app`)

Pass `{ request: { action, ... } }` to `dohc_publish_app`:

- **App-only local approval**:
  1. `{ action: "prepareLocal", workspaceId, appRoot }` -> returns `approvalId`, `candidateDigest`.
  2. `{ action: "approve", workspaceId, approvalId, candidateDigest }` -> returns `publicationId`.
  3. `{ action: "launchLocal", workspaceId, publicationId }` -> returns a local `url` while dohc is open.
- **Combined app + Collection staging** (creates or migrates bound Collections and approves the local app in one review):
  1. `{ action: "stage", workspaceId, appRoot, migrations?: { "<datasetPath>": "<migration.sql>" } }` -> returns `stage.stageId` and `stage.reviewDigest`. Omit a Collection's entry from `migrations` (or omit `migrations`) for operations-only updates without schema SQL changes.
  2. `{ action: "approveStaged", workspaceId, stageId, reviewDigest }` -> applies Collection changes and activates the local app.
- **Rolling back a local approval**:
  1. `{ action: "listLocal", workspaceId, appRoot }` -> returns `publications` (active approval) and up to 3 earlier approved versions in `history` (newest first).
  2. `{ action: "reviewReactivation", workspaceId, publicationId }` -> prepares the stored earlier bundle for review (re-binding Collection operations if the Collection changed without removing or changing those operations) and returns `approvalId`, `candidateDigest`. Restoring changes only the approved bundle, not the source files on disk.
  3. `{ action: "approve", workspaceId, approvalId, candidateDigest }` -> switches this device back to the restored version.
- **Iterating safely on a live app**:
  - Do not use a workspace Version to iterate on an app; non-Main versions run read-only previews and refuse Collection schema or rule changes.
  - For incremental edits, edit the app in place and rely on earlier versions in `listLocal` `history` to roll back if needed.
  - For a side-by-side rewrite over the same Collection (for example `Money v3/` beside `Money/`), create a sibling app folder with its own `app.publish.json` pointing at the same `datasetPath`. When the new app needs different backend logic, add new Collection operations (for example `catalogGetV3`) rather than mutating operations the existing app depends on. Adding an operation changes the Collection's `operationsSha256`, so existing sibling apps still require re-approval (`dataset permissions` `boundApps` shows `needs-refresh`), but they remain re-approvable without changing their source code.

## Publishing to a share link (`dohc_publish_app`)

`createLink`, `prepare`, and `approve` need a workspace that syncs with a server. Without one, they fail with "Sync this workspace before sharing." Check live sync with `dohc_workspace_status` or `dohc workspace status` (`role`, `synced`, `sync.state`, `sync.caughtUp`, `sync.pendingChangeCount`, `sync.lastSyncedAtMs`, `syncFailure`). The `synced` field in `.dohc/sync-history.json` does not show whether the workspace syncs now. For regular file and note writes, `sync.state` and `sync.pendingChangeCount` cover edits the engine has already recorded, so also verify that `sync.lastSyncedAtMs` is later than the write and `pendingShare` is empty. After `approve`, link holders' reads and writes run on that server, so the app works while the owner's computer is off.

1. **Create link**: `{ action: "createLink", workspaceId, appRoot, operationId: "<fresh UUID>" }` -> returns `shareId`, `grantId`, and one-time bearer `url`. Reuse the same `operationId` on retry.
2. **Prepare**: `{ action: "prepare", workspaceId, appRoot, shareId, grantId }` -> returns `approvalId`, `candidateDigest`.
3. **Approve**: `{ action: "approve", workspaceId, approvalId, candidateDigest }` -> returns `publicationId` and `appQuery` (`?app=<publicationId>`).
4. Append `appQuery` before the `#` fragment of the share link URL. Keep the share link secret out of workspace files and dohc requests.

A share link URL is a bearer credential at its stated access level: anyone holding it can use it. An app for members returns no `appQuery`. Rotating a link stays in the desktop. `agentLabel` values are what the agent declares, shown as provenance.

## Personal apps (only in a workspace you joined)

"Personal app" means a private local app inside a workspace someone else owns (`role: "joined"` in `dohc_workspace_status` or `dohc workspace status`). It does not apply to a workspace you own (`role: "owner"`), even if that workspace is named "Personal".

In a workspace you joined, you can open workspace apps published by the owner (`dohc_list_member_apps`) and build private Personal apps on this computer. `personalFolder` returns your Personal app folder on this computer. `prepareLocal`, `listLocal`, and `checkLocal` take one of its subfolders as `appRoot`, and `approve`, `cancel`, `launchLocal`, and `withdraw` work as they do in a workspace you own. A Personal app stays on this computer, never syncs, and runs only the Collection actions your own access allows.

## Opening an app on another device and publishing to workspace members (`dohc_publish_app`)

Apps reach other devices in three distinct ways:

- **Owner's other desktop**: syncs the workspace's files and approves the app locally (`boundApps` `scope: "local"`).
- **Owner's phone (including solo workspaces with no members)**: dohc Desktop auto-publishes an `audience: "owner"` version to the server when the workspace is caught up. `app list` only lists `link` and `workspace` publications. For apps bound to a Collection, check `dataset permissions` `boundApps` for `scope: "owner"` and `status: "compatible"` (apps without Collection bindings have no `boundApps` entry, and phone launch checks approval separately). The owner gets every bound operation (`owner`, `helper`, and `link`).
- **Workspace with invited members (`audience: "workspace"`)**: requires at least one invited member on the workspace (a solo workspace refuses with a conflict until someone is invited):
  1. **Prepare**: `{ action: "prepare", workspaceId, appRoot, audience: "workspace" }` -> returns `approvalId`, `candidateDigest`. Omit `shareId` and `grantId`.
  2. **Approve**: `{ action: "approve", workspaceId, approvalId, candidateDigest }` -> returns `publicationId`.
  3. **Verify that members can open and use it** before you say the app works. Don't ask a person to test it on their phone:
     - Check `dohc_workspace_status` (`dohc workspace status`) shows `sync.caughtUp`.
     - Call `dohc_publish_app` `{ action: "readiness", workspaceId, publicationId }` (`dohc app readiness`). It reads the server's current state and changes nothing. The app opens only when `state` is `"active"` and every `collections[].state` is `"ready"`. Each `members[]` entry, keyed by `memberId` from `dohc members list`, shows `opens`, a `reason` when it doesn't (`outside-app-folder`, `no-collection-access`, `app-unavailable`), and per Collection the `access` and `operations` that member can run. An action the app needs that's missing for a member means it fails for them. Fix it with workspace defaults (step 5) or a data grant, not by asking the member.
     - Call `dohc_publish_app` `{ action: "verifyFrontend", workspaceId, publicationId, memberId, steps }`. It runs the exact bundle the server serves members, against an empty ephemeral Collection, and lets backend calls run only that member's actions. It creates no link, uses no member credential, and never touches live records. It stops with `publication_not_ready` or `member_cannot_open` when readiness says members can't open the app.
     - Call `dohc_list_member_apps` (`dohc member-apps list`) to confirm the signed-in account can open the official `kind: "workspace"` app and read its `url`.
     - Call `dohc_publish_app` `{ action: "list", workspaceId, appRoot }` (`dohc app list`) to inspect active `audience: "workspace"` publications, their `sourceRevision` (compare with `checkLocal`), and their bound `datasetCapabilities[].operations`.
     - Call `dohc_dataset` `{ action: "permissions", workspaceId, datasetPath }` (`dohc dataset permissions`) to confirm `place.kind === "server"`, `boundApps` shows `status: "compatible"`, and `defaults` is current (matching `rules.revisionSha256` proves defaults are active; compatible revisions such as a Collection rename can also preserve defaults pinned to an earlier approved revision).
  4. **Operation access in a workspace-audience app**:
     - **Owner** (on any device signed in as the workspace owner): gets every bound operation in the app (`owner`, `helper`, and `link`).
     - **Member (including an Admin)**: opens the app only while they can see the app folder, its inputs, and every bound Collection. Below Edit, they run only read-only actions. Never gets `owner`-only actions. Gets only bound operations present in the cumulative workspace defaults for their effective level (`view` gets `view`; `comment` gets `view` + `comment`; `edit` gets `view` + `comment` + `edit`) or in their current explicit `kind: "data"` grant. Even `access: "link"` operations must appear in those defaults or a grant. Defaults pinned to an incompatible revision grant nothing. Admins get read access to direct Collection queries (`dohc_collection_access`), not extra operations inside a workspace-audience app.
  5. Set defaults with `dohc_dataset` `{ action: "setDefaults", workspaceId, datasetPath, defaults: { view, comment, edit, revision, revisionSha256 } }`. Defaults never include owner-only actions, and `view` and `comment` defaults are read-only. Take `revision`, `revisionSha256`, and the actions to choose from out of `permissions` `rules`. An Admin of a workspace they joined does the same with `dohc_collection_access`.

## Re-approving apps after a standalone Collection migration

1. Inspect `boundApps` returned by `prepareSchemaChange`, `prepareMigration`, `prepareRelationChoices`, `prepareHistoryRestore`, or `dataset permissions`.
2. Each entry reports `scope` (`"local"`, `"link"`, `"workspace"`, or `"owner"`), `appRoot`, `shareId`/`grantId` (for share links), `status` (`"compatible"`, `"needs-refresh"`, or `"incompatible"`), and plain-English `reasons` when incompatible. If `boundAppsIncomplete` is `true`, check `dataset permissions` after applying the change.
3. For `"incompatible"` apps, update the app's source or `app.publish.json` to match the changed actions or fields first.
4. For older apps whose `app.publish.json` still pins `revision` and `revisionSha256`, remove those two fields once.
5. Re-approve each affected local app with `prepareLocal` + `approve` (or `stage` + `approveStaged`), and each affected share-link app with `prepare` + `approve` using its `shareId` and `grantId`. Re-publishing a share-link app returns a new `appQuery` (`?app=<newPublicationId>`); withdraw the previous `publicationId` explicitly when ready.
