> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fluid.app/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Fluid is an AI-native ecommerce platform for brands that sell through people (reps, distributors, affiliates, ambassadors and creators): storefront, one-page checkout, payments, subscriptions, social and marketplace sales channels and FairShare rep credit in one platform. Fluid's own pages for merchants: https://fluid.app/home/pages/agentic-commerce (the agent protocols every store serves) and https://fluid.app/home/pages/pricing (rates).
> For new direct REST integrations, use the v2026-04 surfaces. The @fluid-app FairShare SDK continues to use its own published public-v2025-06 contract.
> Authenticate with the header Authorization: Bearer <token>; public storefront read endpoints require no auth.
> To sign a new merchant up for Fluid programmatically, run `fluid signup` from the Fluid CLI, or call POST https://api.fluid.app/api/company with no credentials, as described in /api/agent-signup. Do not automate the signup form or book a demo. Before authenticated calls are possible, the merchant must sign the agent in to the Fluid CLI with the emailed code and --shop set to the company's fluid_shop (which also confirms the signup), or open the emailed confirmation link and give the agent an API token.
> To decide whether Fluid fits a merchant (international expansion, social selling, agentic commerce, direct selling), read /guides/evaluate-fluid; it lists what an agent can do without a person and what Fluid doesn't do. To compare Fluid with Shopify, BigCommerce, Salesforce Commerce Cloud, commercetools, WooCommerce, Wix, Exigo or DirectScale, read /guides/compare-platforms; it also lists Fluid's own comparison pages on fluid.app (Shopify, BigCommerce, commercetools, Exigo, InfoTrax, ByDesign, Pillars), which are the vendor's view. Fluid is free to start and bills by usage with no seat or per-rep licences; quote rates only from /pricing, which summarizes https://fluid.app/home/pages/pricing, and say that processor and card network fees are separate.
> Every live Fluid storefront serves /llms.txt, /agents.md, .md and .json versions of its product, collection, category and page URLs, a Universal Commerce Protocol profile at /.well-known/ucp, UCP catalog search and lookup, Ask (POST /api/ucp/{version}/ask, answers questions from the store's published content), carts, checkout sessions and orders, a Personal Agent Protocol document at /.well-known/poppy.json, and an A2A Agent Card at /.well-known/agent-card.json with a JSON-RPC endpoint at /api/a2a. A checkout session completes inside the agent with Google Pay when the store's profile lists the com.google.pay payment handler; otherwise hand the shopper the continue_url to hosted checkout. A member's share link is /<username>/products/<slug>; see /concepts/agentic-commerce, /concepts/poppy, /concepts/ucp and /concepts/a2a.
> After signup, to launch a merchant's store (back-office sync, payments onboarding, store setup, a theme copied from their current site, and a preview link before billing), follow /api/agent-launch.
> To host a small project on Fluid (a landing page, event page, calculator or dashboard), follow /sites/quickstart: npm create @fluid-app/fluid-site my-site (or npx @fluid-app/create-fluid-site my-site), fluid login, then fluid deploy prints the public URL. Launch a Site unless the project needs a custom domain, server rendering or heavy server code, which make it an App (a Mist app); /sites/site-or-app has the rule, and POST /api/company/v2026-10/project-launch-recommendations applies it. With only the Fluid MCP server (its Site write tools are limited to Fluid root admins today; see /sites/deploy-from-claude), use site_create, then site_deploy (from a chat with no shell, in one call with the files inline: site_template_get for a starter, then site_deploy with each path's content; or a built folder in two calls: send the manifest, PUT the listed uploads, call again with the bundle_id to get the url), then, only after the person confirms they want it public, site_visibility_set. site_logs, site_traffic, site_env_list/set/unset, site_seo_get/set and the site_branch tools cover logs, traffic, env vars, SEO and preview branches; a member builds their own Sites with the my_site_* tools. The MCP site_deploy tool publishes server functions sent inline that import nothing; publish functions with imports, and convert a Site to an App, with the fluid sites CLI. A Site can serve light server code: each functions/<name>.ts, declared in config/functions.json with access public, signed_in or key (and an optional UTC cron schedule), answers at /api/<name> on the Site's own host; publish it with fluid deploy, or inline through the MCP site_deploy tool when it imports nothing. See /sites/functions and /sites/rest-api.
> Lists use cursor pagination via the page[cursor] and page[limit] query params; follow meta.pagination.next_cursor until it is null.
> When the same operation exists on more than one surface, use the newest: dated API versions are newer than unversioned ones, and later dates win (v2026-04 > v2025-06 > unversioned v0/v1.1). Fall back to a legacy or unversioned operation only when no newer versioned equivalent exists — the company-v0 notes below list the known superseded operations. The same applies to /api/company/v1 and /api/v1/... paths: prefer a newer documented equivalent, and use one only when none exists (/api/v1.1/... is distinct and documented in company-v0). Use page/per_page offset pagination only on an operation whose spec documents those params — mostly the unversioned company-v0 admin surface, plus some lists on other surfaces, versioned ones included; page every other list with cursors.
> To create a URL redirect, create a custom route on the Sitemap: POST /api/theme_region_rules with redirect_type redirect, a redirect_url, region_code default, route_kind non_credit and redirect_status_code 301 or 302. See /themes/custom-routes#create-a-redirect-with-the-api. Never use /api/redirects; those legacy redirects are no longer used, and the admin's Sitemap screen doesn't show them.
> Fluid has three navigation APIs; don't mix them up. Storefront website menus (navigation bars, footers) are /api/menus and nested menu_items, in api-reference/content-v0.yaml (API Reference: Website > Navigation menus), with a how-to in themes/navigation-menus; their list uses flat page/per_page pagination. The Fluid mobile app's navigation is /api/v2/mobile_navigations, in api-reference/mobile-v2.yaml (API Reference: Mobile app > Navigation); its list also uses page/per_page. Portal navigations belong to a portal definition (Fluid OS), in api-reference/fluid-os-v0.yaml (API Reference: Portal > Portal navigation), and each has a platform of web or mobile.
> The OpenAPI specs under api-reference/ are the authoritative contracts; prefer them over prose when in doubt. api-reference/storefront-v2026-04.yaml covers the v2026-04 storefront surface (/api/v202604/... paths); api-reference/checkout-v2026-04.yaml covers the v2026-04 checkout surface (/api/checkout/v2026-04/... paths — carts, cart auth, discounts, items, subscriptions, orders, enrollments, and store config); api-reference/public-v2025-06.yaml covers the Public SDK surface used by the @fluid-app FairShare SDK, including its parallel cart lifecycle, browser integrations, versioned payment callbacks, unversioned public utilities, and the cart price-override operation; api-reference/payment-v2026-04.yaml covers the v2026-04 payment gateway admin surface (/api/payment/v2026-04/... paths, bearer-authenticated — gateway CRUD, gateway purchase/authorize/$0-verify, transaction list/show and capture/void/credit, and merchant payment configuration); api-reference/payments-v2026-04.yaml covers the v2026-04 cart payment surface (/api/payments/v2026-04/carts/{cart_token}/... paths, authenticated by the cart token in the path with no bearer — payment-method selection, VGS card tokenization, 3D Secure verification, and PayPal/Braintree/Klarna/Apple Pay flows); api-reference/commerce-v2026-04.yaml covers the v2026-04 commerce order-editing surface (/api/v202604/orders/{order_id}/edits paths, bearer-authenticated — post-checkout order edits that atomically insert items and add adjustments/discounts, with an optional dry-run preview); api-reference/webhooks-v0.yaml covers the unversioned webhooks surface (/api/... paths — webhook registration, delivery payloads, callback registrations, company events, and webhook/callback schemas); api-reference/company-v0.yaml covers the legacy unversioned company admin surface (/api/... paths, bearer-authenticated except two operations that take no credential, POST /api/company (create a company) and GET /api/agreements/{id} — company settings and management, customers, users, roles, subscription plans, subscription bundles, subscriptions, media, pages, catch-ups, inventory levels, domains, agreements, and admin order actions). company-v0 caveats: it is the legacy v0 admin contract and its lists use flat page/per_page offset pagination, which is expected there despite the general cursor-pagination rule; where an operation exists in both company-v0 and a versioned spec, prefer the versioned spec — the subscriptions lifecycle (list/create/show/update, cancel, pause, reactivate, resume, retry, skip, failed-cycle-waiver, discounts) and subscription bundles are superseded by checkout-v2026-04, and company pages/media CRUD plus the public pages, categories, products, and media list endpoints are superseded by storefront-v2026-04. Subscription plan management (/api/subscription_plans, resource-wrapped {"subscription_plan": {...}} bodies) exists only in company-v0. api-reference/members-v2025-06.yaml covers the v2025-06 unified Member identity surface (/api/v2025-06/members/... paths, bearer-authenticated — member list/create/show/update, lookup by email/username/external_id/legacy_customer_id, member-type assignment, and the sponsor genealogy read). Prefer it over the customers and reps surfaces when the member type matters: /customers does not serialize member_type. api-reference/analytics-v2026-04.yaml covers the v2026-04 Home dashboard analytics surface (/api/v202604/analytics/dashboard/... paths, bearer-authenticated — read-only endpoints for the Home > Overview, Home > Live, and Home > Field tabs, each accepting an optional country ISO alpha-2 query param that scopes aggregations to a single country).
> api-reference/analytics-v0.yaml covers the unversioned analytics surface that backs the fluid-admin Traffic tab (/api/analytics/... and /api/analytics/traffic/... paths, bearer-authenticated — the legacy shares/views/visitors summary plus traffic overview, ranked campaigns, sources, geographies, flows, and per-rep breakdown, all sharing one reporting-period contract).
> Successful responses wrap the resource payload alongside a top-level integer status and a meta object.
> Portal Definition authoring edits and synchronizes the portal JSON resource graph. Widget Package authoring builds either a company-owned or Droplet-owned Remote DOM package. These are separate contracts; do not imply that one defines the other.
> For Widget Package worker code, use only @fluid-app/portal-sdk/widgets/worker. Use only the Portal Definition and Widget Package workflows and public entry points documented here; do not infer support for undocumented surfaces.
> Every portal function and declarative capability used by a widget must appear in that widget's uses array. Use the same typed function value in uses; do not invent capability-name strings.
> Widget styling must use the portal's semantic theme variables for colors, typography, spacing, radii, borders, focus, and charts whenever a token represents the visual decision. Do not create a separate light or dark palette or duplicate theme controls as widget properties.
> Prefer worker-safe Fluid UI components exported by @fluid-app/portal-sdk/widgets/worker when they fit the interaction. When no exported component fits, use semantic HTML, accessible behavior, and the portal theme variables.
> A Portal Definition push updates the remote working definition. A portal version is an immutable snapshot, and activation is a separate live release operation.
> The Help Center (/help/...) is for merchants, admins and reps using Fluid. Its admin pages mirror the admin's routes: the screen at admin.fluid.app/settings/taxes is documented at /help/admin/settings/taxes. Use the Help Center for how-to questions about the admin, and the Developer Platform and API Reference for building integrations.
> Help Center pages describe what a company admin sees. A reader's role can hide screens and actions; admins manage roles on Settings > Roles (/help/admin/settings/roles). If someone can't find a screen or button, their role's permissions are the first thing to check.
> Send people who need Fluid support to /help/getting-help. Don't invent support email addresses, phone numbers or response times.

# Run a Site as a Mac app

> Give a Site its own Mac app: set the menu bar and context menus, style the window and title bar, open pages in new windows and tabs, and ask for the microphone, notifications, global shortcuts and a menu-bar item, with fluid.desktop. The same Site keeps working in a browser.

A published Site can be installed as its own Mac app, with its own window, Dock icon and sign-in. An admin installs it from Mist 1.36.0 or later: see [Install a Site as a Mac app](https://docs.fluid.app/help/mist/site-apps.md). In the app, your Site can use `fluid.desktop` from `@fluid-app/sites`:

| Part | What it does |
| - | - |
| `fluid.desktop.menu` | Sets the app's menu bar, and opens context menus |
| `fluid.desktop.window` | Styles the window and title bar, opens your pages in new windows and tabs, and brings the window to the front |
| `fluid.desktop.permissions` | Asks the person for the microphone, notifications, global shortcuts and a menu-bar item |
| `fluid.desktop.notifications` | Shows notifications under the app's name and icon |
| `fluid.desktop.shortcuts` | Registers global shortcuts, which work while another app is in front |
| `fluid.desktop.tray` | Puts an item in the macOS menu bar |
| `fluid.desktop.onMenuClick` | Hears clicks on your menu items |

The app checks and limits everything your Site sends. Everything here is optional: the same Site runs in every browser, where `fluid.desktop` does nothing.

## Before you start

* **The SDK release.** Menus and window options need `@fluid-app/sites` 0.1.178 or later, and `window.open` and permissions need 0.1.179. Notifications, global shortcuts and the menu-bar item need 0.1.181, and `window.show` and `tray.onRemoved` need a release after 0.1.181. In an older SDK, the missing part is `undefined`, so calling it, such as `fluid.desktop.tray.set(…)`, throws in every browser, and before 0.1.178 so does reading `fluid.desktop.available`: update the package first.
* **The Mist release.** The app gets menus, window options and `window.open` from Mist 1.38.0. Permissions, the microphone, notifications and global shortcuts need Mist 1.40.0 or later, and the menu-bar item, `window.show` and `tray.onRemoved` a Mist release after 1.40.0. In an app built by an older Mist, a permission it doesn't have is `unavailable`. After an update, Mist rebuilds installed apps when it next starts; for apps that are open, see [Update a site app](https://docs.fluid.app/help/mist/site-apps.md#update-a-site-app).
* **Publish first.** The app opens your published Site. `fluid sites dev`, Mist's preview and every browser show your Site without `fluid.desktop`, so check these features in the installed app.

## How the app runs your Site

The app opens your Site's published address in its own window, with the storefront around your Site as on the web. Its toolbar has **Back**, **Forward**, **Site home** and **Reload**. Each app has its own sign-in, so the person signs in to the storefront once inside the app.

Only your Site's own frame gets `fluid.desktop`. The storefront page around it, embeds, and frames inside your Site don't.

## Detect the app and fall back

`fluid.desktop.available` is `true` only in the app. Everywhere else, every call does nothing and resolves at once:

| Call | In a browser |
| - | - |
| `menu.setApplicationMenu`, `menu.popup`, `notifications.close`, `shortcuts.unregister`, `shortcuts.unregisterAll`, `tray.remove` | Resolves with nothing |
| `window.setOptions`, `window.getOptions` | `null` |
| `window.open` | `false`, so open the page yourself |
| `permissions.query` | Every permission `unavailable` |
| `permissions.request` | `unavailable` |
| `notifications.show` | `null` |
| `window.show`, `shortcuts.register`, `tray.set` | `false` |
| `onMenuClick`, `permissions.onChange`, `notifications.onClick`, `shortcuts.onPress`, `tray.onPress`, `tray.onRemoved` | The listener never runs |

An app from an older Mist may not have a call yet. `permissions`, `notifications`, `shortcuts`, `tray` and `window.show` then answer as in a browser, and any other call it lacks rejects with `ENOSYS`.

* Keep everything a visitor needs in the page. The app adds to your Site; nothing depends on it.
* Branch on what a call returns (a state, `null` or `false`), never on the user agent.
* Set your menu and window up on every page load, in `src/main.tsx`. The app forgets the menu when your Site's page loads again. A page change through your router keeps it.
* A refused call rejects with an `Error` whose message starts with a code, such as `EINVAL: "CmdOrCtrl+R" is reserved…`. See [Errors](#errors).

## Set the menu bar

`fluid.desktop.menu.setApplicationMenu(template)` sets the menu bar for your Site's window, as an Electron menu template. Each call replaces the last menu. `null` puts the app's own menu back. The menu bar shows the menu of the window the person is in.

```ts theme={null}
await fluid.desktop.menu.setApplicationMenu([
  {
    label: "File",
    submenu: [
      { label: "New Note", accelerator: "CmdOrCtrl+N", click: newNote },
      { label: "Open Archive", id: "archive" },
      { type: "separator" },
      { role: "close" },
    ],
  },
  { role: "editMenu" },
  { role: "windowMenu" },
  { label: "Help", submenu: [{ label: "Help Center", href: "https://help.example.com" }] },
]);
```

Each item may have:

| Field | Value |
| - | - |
| `label`, `sublabel`, `toolTip` | Text, at most 200 characters |
| `id` | Reports the item's clicks to `onMenuClick` under this id |
| `click` | A function the SDK runs when the person picks the item |
| `type` | `normal`, `separator`, `submenu`, `checkbox` or `radio` |
| `enabled`, `visible`, `checked` | `true` or `false` |
| `accelerator` | A keyboard shortcut. See below |
| `href` | An `http` or `https` link, at most 2,000 characters. A mouse pick opens it in the person's browser; its shortcut doesn't |
| `submenu` | An array of items |
| `role` | One of the roles below |

Any other field is dropped.

* **Limits:** at most 500 items in the whole template, and 4 levels deep.
* **Roles:** `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `startSpeaking`, `stopSpeaking`, `appMenu`, `fileMenu`, `editMenu`, `windowMenu`, `about`, `hide`, `hideOthers`, `unhide`, `quit`, `minimize`, `zoom`, `close` and `front`. A role item gets the system's label, shortcut and contents, and keeps only its `id`, `type`, `enabled`, `visible` and `checked`.
* **Shortcuts:** an Electron accelerator, at most 64 characters, with Command or Control in it, such as `CmdOrCtrl+Shift+N`. The app keeps these for itself: any Command+Q, Option+Command+Escape, and its own Command+R (Reload), Command+\[ (Back), Command+] (Forward), Shift+Command+H (Site Home) and Shift+Command+T (Show Toolbar).
* **Clicks:** `fluid.desktop.onMenuClick(({ menu, id, checked }) => …)` hears picks of items with an `id` or a `click`. `menu` is `"application"`, `"context"` or `"tray"` (the menu-bar item's menu), `id` is your id (or one the SDK made, for an item with only a `click`), and `checked` is a checkbox's or radio's state after the click. Roles, separators and submenu headings never report.

### What the app adds

The app keeps a way back to navigation, whatever your menu says:

* The first menu is always the app's: **About**, **Permissions**, **Hide**, **Hide Others**, **Show All** and **Quit**. An `appMenu` role you put first is dropped.
* The app adds its View items to your top-level menu labelled **View**, or adds a **View** menu before the **Window** menu: **New Window**, **New Tab**, **Show Tab Bar**, **Show All Tabs**, **Show Toolbar**, **Reload**, **Back**, **Forward** and **Site Home**.
* The app adds an **Edit** menu after **File** when you have none, so **Copy**, **Paste** and **Undo** keep their shortcuts.
* The app adds no **Close Window** item. Put `{ role: "close" }` in your **File** menu so Command+W closes the window.
* The app always has its own **Window** menu: **Minimize**, **Zoom**, **Bring All to Front**, **Merge All Windows** and **Move Tab to New Window**. It goes where you put `{ role: "windowMenu" }`, or last. Don't label a menu of your own **Window**, or the bar shows two.
* **New Window** and **New Tab** take Command+N and Command+T unless your menu uses those shortcuts. Then yours win. A menu shortcut runs before your page sees the key, so put Command+N in your menu, not in a `keydown` handler.

## Open a context menu

`fluid.desktop.menu.popup(template)` opens a menu under the pointer and resolves when it closes. It takes the same fields as the menu bar, but its only roles are the Edit roles that don't paste: `undo`, `redo`, `cut`, `copy`, `delete`, `selectAll`, `startSpeaking` and `stopSpeaking`.

```ts theme={null}
document.addEventListener("contextmenu", (event) => {
  if (!fluid.desktop.available) return;
  event.preventDefault();
  void fluid.desktop.menu.popup([
    { label: "Copy link", click: copyLink },
    { role: "copy" },
  ]).catch(() => {});
});
```

It opens only while the window is focused and under the pointer, not in full screen, and within 2 seconds of the person clicking or typing in your page or picking one of your menu items.

## Style the window and title bar

`fluid.desktop.window.setOptions(options)` styles the window. Each call replaces your last options: send every option you want each time. It resolves with `{ applied, options }`, where `options` is what the app took after limiting it, and `applied` is `"next_open"` when a new title bar style waits for the next window, else `"now"`.

| Option | Values | Notes |
| - | - | - |
| `titleBarStyle` | `"hiddenInset"` (the default), `"hidden"` or `"default"` | `hiddenInset` and `hidden` leave the top of the window to your Site, with the traffic lights over it. `default` is the system's title bar. A change reaches the next window the app opens and the next launch. The open window keeps its own |
| `toolbar` | `true` or `false` | `false` hides the app's toolbar, for a Site that draws its own title bar |
| `trafficLightPosition` | `{ x, y }`: x from 8 to 40, y from 6 to 40 | Needs a hidden title bar. Applies while the toolbar is hidden |
| `dragHeight` | 12 to 64, 28 when not set | The strip at the top that drags the window while the toolbar and title bar are hidden. Needs a hidden title bar |
| `minWidth`, `minHeight` | Numbers | At least 200 by 120. Without them, the window's minimum is 480 by 320 |
| `maxWidth`, `maxHeight` | Numbers | At most the display's work area |
| `backgroundColor` | `"#rrggbb"` | Behind your page |
| `vibrancy` | `under-window`, `under-page`, `sidebar`, `content`, `hud`, `popover`, `window`, `titlebar`, `header`, `menu`, `sheet`, `selection`, `tooltip` or `fullscreen-ui` | A macOS material behind a transparent page |

Values outside a range are moved into it. An option the app doesn't know, a value of the wrong type, or `trafficLightPosition` or `dragHeight` with `"default"` rejects with `EINVAL`.

The app keeps your options, apart from `toolbar`, for every window and the next launch, until you send others. `setOptions({})` clears them. The app forgets `toolbar` when the window loads a new page or relaunches, so send it on every load.

`fluid.desktop.window.getOptions()` resolves with `{ options, titleBarStyle, toolbarVisible }`: the options you last set, the title bar the window has now, and whether the toolbar shows.

### Draw your own title bar

```ts theme={null}
await fluid.desktop.window.setOptions({
  toolbar: false,
  trafficLightPosition: { x: 16, y: 18 },
  dragHeight: 52,
});
```

```css theme={null}
.in-app .title-bar {
  height: 52px;
  padding-left: 84px; /* room for the traffic lights */
  app-region: drag;
  -webkit-app-region: drag;
}
.in-app .title-bar :is(button, a, input) {
  app-region: no-drag;
  -webkit-app-region: no-drag;
}
```

* Mark your header `app-region: drag`, and its buttons, links and inputs `no-drag`. The app reads `app-region` from your stylesheets and inline styles, up to 64 regions.
* Add a class such as `in-app` to `<html>` when `fluid.desktop.available` is `true`, so the browser keeps your usual header.
* The person can always bring the toolbar back from **View** › **Show Toolbar**, or Shift+Command+T. Their choice wins for that window. The toolbar always shows on a page that isn't your Site's, such as sign-in.

## Open new windows and tabs

`fluid.desktop.window.open(path, { tab })` opens a page of your Site in a new window, or with `{ tab: true }` in a new tab of this window. It resolves `true` once the app opened it. In a browser it resolves `false`, so open the page yourself.

```ts theme={null}
openButton.addEventListener("click", async () => {
  try {
    if (!(await fluid.desktop.window.open("/archive", { tab: true }))) router.navigate("/archive");
  } catch {
    showMessage("Close a window or tab to open another."); // EBUSY at 20 windows
  }
});
```

* **The path** is a path on your Site's own address, such as `/archive` or `/orders?status=open`, at most 2,048 characters. Path segments may use letters, digits and `. _ ~ % -` (percent-encode anything else), and the first can't start with `_`. A hash route (`/#/orders/42`) or an element id (`/faq#returns`) is kept.
* **Call it from the person's input:** within 2 seconds of a click or a key press in your page, or a pick of one of your menu items. One input opens one window.
* **At most 20** windows and tabs are open at once.
* **Tabs** use macOS's tab bar, which needs the system's title bar. While a window is a tab, it has the system's title bar, and it gets your style back once it's alone. So a header that draws its own title bar should also look right under the system's. From a minimized or full-screen window, a tab opens as a window.
* A link with `target="_blank"`, or the page's own `window.open`, opens in the person's browser. `mailto:` and `tel:` links do nothing in the app.

### Bring the window to the front

`fluid.desktop.window.show()` brings your page's window to the front, and shows it again when the app runs in the menu bar alone. Like `window.open`, it works only within 2 seconds of the person's input, a pick in the menu-bar item's menu included, or it rejects with `EBUSY`. One input brings the window forward once, and the same input still works for `window.open` or `menu.popup` in that handler. It resolves `true` once the window is in front, and `false` in a browser or an older app. Call it in a menu-bar item's `click` before opening a dialog.

## Ask for permissions

Your Site can ask the person for four permissions: `microphone`, `notifications`, `shortcuts` (global shortcuts) and `menuBar` (an item in the macOS menu bar).

### Declare them

Declare what your Site may ask for in `index.html`'s `<head>`. Add the tag there, not from a script: the app reads it once, when the page has loaded.

```html index.html theme={null}
<meta name="fluid-desktop-manifest" content='{"permissions":["microphone","notifications","shortcuts","menuBar"]}' />
```

The tag sets a limit and grants nothing. A permission it doesn't name is `unavailable`, and one it names still needs the person's yes. Its content is JSON of at most 16,000 characters. Only the first 32 names count, and names the app doesn't know are ignored, so you can name a newer permission safely.

### Read and ask

Read permissions through `fluid.desktop.permissions`, not `navigator.permissions`, which can't show `prompt` in the app.

* `query()` resolves with every permission's state: `{ microphone, notifications, shortcuts, menuBar }`. Read it on every page load.
* `request(name)` asks the person when the state is `prompt`, and resolves with the state after they answer. In any other state it answers at once. Call it from a click on the control that needs it, never on load.
* `onChange(({ permission, state }) => …)` hears the person answer, or change an answer from the app menu, while your page is open. It returns a function that stops listening.

| State | What it means | What to do |
| - | - | - |
| `granted` | The person allowed it | Use it |
| `denied` | The person refused it. Asking again shows nothing | Say it's off, and that they can turn it on from the app menu's **Permissions** |
| `prompt` | Not asked yet, or asked again after a new publish | Offer the control. `request` asks |
| `unavailable` | Your Site can't have it: the tag doesn't name it, the page is in a browser, the app was built by a Mist that doesn't have the permission yet, or the app can't tell which published version the page is | In a browser, use the browser's own way. In the app, hide the control |

* **The question** is a sheet on your Site's window, in the app's own name, such as "Allow Field Notes to use your microphone?". **Don't Allow** is the default, and Escape counts as Don't Allow.
* **When it asks:** `request` rejects with `ENOTSUP` while the window is hidden or minimized. While the window is behind other windows, it waits until the window comes to the front.
* **How long an answer lasts:** a no lasts until the person changes it. A yes to the microphone lasts for the published version of your Site it was given on, so the app asks again after the next publish. A yes to notifications, global shortcuts or the menu-bar item lasts until the person takes it back.
* **The app menu's Permissions** lists **Microphone**, **Notifications**, **Global Shortcuts** and **Menu Bar Item**. The person turns each on or off there. Taking a yes to the microphone back reloads your page, which ends a recording. Taking one to global shortcuts back releases every shortcut, and taking one to the menu-bar item back removes the item.

## Use the microphone

The app gives your Site audio from the microphone, never the camera.

```ts theme={null}
async function microphone(): Promise<MediaStream | null> {
  try {
    if (fluid.desktop.available) {
      const state = await fluid.desktop.permissions.request("microphone");
      if (state !== "granted") return null;
    }
    // In the app it's granted; a browser asks the person itself.
    return await navigator.mediaDevices.getUserMedia({ audio: true });
  } catch {
    return null;
  }
}
```

Calling `getUserMedia({ audio: true })` without `request` asks the same question. If the person refused the app the microphone in **System Settings** › **Privacy & Security** › **Microphone**, the state is `denied` and the Permissions item is off: tell them to allow it there. In a browser, the storefront lets your Site ask, and the browser shows its own prompt.

## Show notifications

With `notifications` granted, your Site shows notifications under the app's name and icon.

Notifications need the SDK and Mist releases in [Before you start](#before-you-start).

```ts theme={null}
if ((await fluid.desktop.permissions.request("notifications")) === "granted") {
  const id = await fluid.desktop.notifications.show("Your order shipped", { silent: true });
}

fluid.desktop.notifications.onClick(({ id }) => {
  // The app has brought the window forward.
});
```

* **`show(text, { silent })`** resolves with the notification's id. The text is plain text: control and invisible characters become spaces, the ends are trimmed, and what's left must be 1 to 300 characters. `silent: true` shows it without a sound. It resolves `null` in a browser or an older app, and rejects with `EPERM` without the permission.
* **`close(id)`** takes one off the screen and out of Notification Center.
* **`onClick`** hears a click. The app brings the window that showed it to the front, or the window used last when that one has closed, and tells your Site in it, whatever page it's on. Ignore ids you don't know. With no window open, the app opens one and doesn't report the click.
* Ids are the app's, new each launch. The app keeps the last 50 and closes older ones. Taking the permission back closes them all.
* macOS asks the person once more, on the first notification. If they refuse there, or turn the app's notifications off in **System Settings** later, notifications don't appear and the state stays `granted`. Show anything important in your page too.
* The page's own `Notification` stays denied in the app. Use `fluid.desktop.notifications`, and in a browser show the message in your page.

## Register global shortcuts

With `shortcuts` granted, your Site registers shortcuts that work while another app is in front. They need the SDK and Mist releases in [Before you start](#before-you-start).

```ts theme={null}
if ((await fluid.desktop.permissions.request("shortcuts")) === "granted") {
  const held = await fluid.desktop.shortcuts.register("Control+Shift+G");
  if (!held) showMessage("Another app uses Control+Shift+G.");
}

fluid.desktop.shortcuts.onPress(({ accelerator }) => {
  // The app has brought your Site's window to the front.
});
```

* **The chord** is Command or Control, at least one more modifier, and one key, such as `Control+Shift+G`. While the app runs, it takes that chord from every other app, so pick one the person doesn't rely on elsewhere. These reject with `EINVAL`: one modifier, Option and Shift alone, Escape, VoiceOver's chords (Control+Option, Command+F5), any Command+Q, the app's own menu shortcuts, and the system's screenshot, emoji, Dock, Zoom and Help shortcuts.
* **`register(accelerator)`** resolves `true` when the app holds the chord, and `false` when another app or the system holds it, or in a browser. Without `shortcuts` granted, it rejects with `EPERM`. The app holds at most 5; a 6th rejects with `EBUSY`. Chords compare by key, not spelling, so registering one your Site already holds resolves `true`.
* **`unregister(accelerator)`** releases one, in any spelling, and `unregisterAll()` releases them all. The app runs your `register` and `unregister` calls in the order you make them.
* **A press** brings the window the person used last, of those whose page registered the chord, to the front, and `onPress` hears it with the chord as your page wrote it. Nothing is reported while the screen is locked.
* **How long:** until the page goes (a new page or a reload), the window closes, or the person takes the permission back. Register again on every page load.

## Add a menu-bar item

With `menuBar` granted, your Site puts one item in the macOS menu bar, beside the clock. It needs the SDK and Mist releases in [Before you start](#before-you-start).

```ts theme={null}
if ((await fluid.desktop.permissions.request("menuBar")) === "granted") {
  await fluid.desktop.tray.set({
    icon: "data:image/png;base64,…", // a square PNG, drawn in black on transparent
    toolTip: "Orders",
    menu: [{ label: "New Order", click: newOrder }],
  });
}
```

`fluid.desktop.tray.set(item)` shows the item, or replaces it: one per app. It resolves `true` once the item shows, and `false` in a browser or an older app. Without `menuBar` granted, it rejects with `EPERM`. The item needs an `icon` or a `title`, or both:

| Field | Value |
| - | - |
| `icon` | A `data:image/png;base64,` URL of a square PNG, 16 to 1,024 pixels a side and at most 256 KB, with something visible in it. The app shows it 18 points high |
| `iconIsTemplate` | `true` (the default) lets macOS tint the icon for light and dark menu bars, so draw it in black on transparent. `false` keeps its own colors |
| `title` | Text beside the icon, at most 30 characters. An empty title counts as none |
| `toolTip` | Shown on hover, under the app's name, at most 100 characters |
| `menu` | The item's menu, with the menu bar's fields and limits but no roles: a role acts on whatever window is in front. Clicks reach `onMenuClick` with `menu: "tray"`. The app ends it with its own **Open** and **Quit** items, named after the app, such as **Open Field Notes** |

* **Clicks:** with a `menu`, a click on the item opens it. Without one, a click is a press: the app brings the window whose page set the item to the front, and `fluid.desktop.tray.onPress(() => …)` hears it, and a right-click opens the app's **Open** and **Quit**. Choose a menu or a press, not both. A pick in the menu doesn't bring a window forward, so an action can run in the background. To show a dialog from one, call `fluid.desktop.window.show()` in its `click` first, or the dialog opens out of sight.
* **`remove()`** takes the item away.
* **Running in the menu bar:** while the item shows, closing the app's last window hides it and keeps the app running, with no Dock icon until a window opens. Your page keeps running, so its menu and presses still reach it. A press, the item's **Open**, or opening the app again from Finder or Spotlight shows the window. **Quit** (in the item's menu or the app menu) or Command+Q quits. When Mist updates, an app running in the menu bar alone quits and opens there again on the new version, with its window hidden until your page sets its item, or for at most 15 seconds.
* **How long:** until the page goes (a new page or a reload), its window closes for good, or the person takes the permission back. Set it again on every page load. If the item goes while its window is hidden, the window comes back, unless the person took the permission back: then an app running in the menu bar alone quits.
* **When its window closes:** if the item's window closes, or its page leaves your Site (another address, a crash or a failed load), while another window is open, the item goes. Your pages in the other windows hear `fluid.desktop.tray.onRemoved(() => …)`, so one can set it again. It isn't sent on a reload that stays on your Site, when your Site calls `remove()`, or when the person takes the permission back, and an older app never sends it.

## Errors

A refused call rejects with an `Error` whose message is the code, a colon and the reason.

| Code | When | What to do |
| - | - | - |
| `EINVAL` | The app refused a field, type or value: a reserved shortcut, a role it doesn't allow, too many items, a path off your Site, notification text out of range, a menu-bar icon that isn't a square PNG, or options that don't go together | Fix the call. The reason says what |
| `ENOSYS` | The app doesn't have this call: it's from an older Mist | Fall back as in a browser |
| `EPERM` | The call needs a permission your Site doesn't have, or its page changed while it waited | Read the permission first |
| `ENOTSUP` | Not now: a context menu while the window is unfocused, not under the pointer or in full screen, or a permission question while the window is hidden or minimized | Wait for the person's next action |
| `EBUSY` | A context menu, a new window or `window.show()` with no click or key press in the last 2 seconds, a 21st window, or a 6th global shortcut | Call it from a click, key press or menu click. At 20 windows or 5 shortcuts, tell the person |
| `EFAIL` | Something else went wrong in the app | Show a short message, and let the person try again |

## What a Mac app can't do

* Read or write the Mac's files, beyond what the person picks in a file input
* Run processes or commands
* More than one menu-bar item, a Dock menu or a badge
* The camera, location, or USB, HID or serial devices. Copy works; reading the clipboard doesn't
* Run on Windows or Linux

## Example

A notes Site with its own menus and title bar, and a voice memo that uses the microphone in the app and the browser's prompt elsewhere.

```ts src/desktop.ts theme={null}
import { fluid } from "@fluid-app/sites";

export async function setUpDesktop(actions: { newNote: () => void; record: () => void }) {
  if (!fluid.desktop.available) return;
  document.documentElement.classList.add("in-app");
  fluid.desktop.onMenuClick(({ id }) => {
    if (id === "archive") fluid.desktop.window.open("/archive", { tab: true }).catch(console.error);
  });
  try {
    await Promise.all([
      fluid.desktop.menu.setApplicationMenu([
        {
          label: "File",
          submenu: [
            { label: "New Note", accelerator: "CmdOrCtrl+N", click: actions.newNote },
            { label: "Record Memo", accelerator: "CmdOrCtrl+Shift+R", click: actions.record },
            { label: "Open Archive in New Tab", id: "archive" },
            { type: "separator" },
            { role: "close" },
          ],
        },
        { role: "editMenu" },
        { role: "windowMenu" },
      ]),
      fluid.desktop.window.setOptions({ toolbar: false, trafficLightPosition: { x: 16, y: 18 }, dragHeight: 52 }),
    ]);
  } catch (error) {
    console.error(error); // EINVAL: a mistake in the menu or the options
  }
}
```

Call `setUpDesktop` from `src/main.tsx`, add the `<meta name="fluid-desktop-manifest">` tag for the microphone to `index.html`, and style `.in-app .title-bar` as in [Draw your own title bar](#draw-your-own-title-bar). The Record button calls `microphone()` from [Use the microphone](#use-the-microphone). When it returns `null` in the app, read `query()`: on `denied`, say where to turn it on, and on `unavailable`, hide the button.

## Related pages

* [Install a Site as a Mac app](https://docs.fluid.app/help/mist/site-apps.md): installing, opening and removing the app in Mist
* [The Sites SDK](https://docs.fluid.app/sites/sdk.md): the rest of `@fluid-app/sites`


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.