# That Open Platform — AI Quick Start (zero to a running app or cloud component)

You are an AI assistant. A user pointed you at this URL so you can scaffold and run something
on the [That Open Platform](https://platform.thatopen.com) from scratch, using
`@thatopen/services` (the `thatopen` CLI + client library). Follow the steps below in order.

> The only secret you need is a **platform API token** — **not** an npm token. The CLI
> derives private beta-registry access from the platform token automatically.

---

> **Not building anything — here to USE an app the user has open?** If the user wants you to do
> something in an app that is already running on the platform ("make me drawings in the app I have
> open", "check this model", "count the doors"), you build nothing and install nothing but the MCP
> server. Nothing below applies past these steps:
>
> 1. **You need the `thatopen mcp` server** (section 5e below has the config to add). If your
>    tools do not include `send-app-command`, tell the user to add it to their MCP client and
>    restart it. You cannot add it yourself from a chat.
> 2. **Get the URL of the app tab**: `https://<platform>/dashboard/projects/<project>/apps/<app>`.
>    Ask the user for it if they did not give it. Pass that URL as `project`, and the server reads
>    the project and the app from it.
> 3. **Send `help` first.** Each app declares its own commands. Its `help` reply lists them and
>    says how the app wants to be used, and some apps point on to a longer `guide`. That reply is
>    the manual: follow it, not your guesses about the app.
> 4. Then do what was asked, one command at a time, reading every reply. `delivered: 0` means the
>    app tab is not open (or needs a reload): ask the user, then retry.
>
> Phrases that mean this: *"in the app I have open"*, *"use Planner/Coordinator to…"*, *"drive
> my app"*, *"make me a set of drawings"*.

> **Not building anything — here to work in Revit?** If what the user actually wants is to share a
> Revit model with their team, join one a colleague uploaded, or bring an IFC or a Rhino model into
> their Revit model with a recipe that already exists, this is the wrong guide and nothing below
> applies. Go to
> **[the Revit collaboration quickstart](https://raw.githubusercontent.com/ThatOpen/platform_services/main/docs/revit-collab-quickstart.md)** and follow that instead.
> It is the same shape as this one: ask first, then drive the CLI.
>
> Phrases that mean that guide, not this one: *"I want to collaborate on a Revit project"*, *"share
> my central"*, *"join my team's model"*, *"bring this IFC into my Revit model"*, *"work on the
> same model as my colleague"*.
>
> *"Someone sent me a change to approve"* has no guide: nothing is sent into anybody's model any
> more, and there is nothing to approve. What exists is the person in Revit applying a recipe
> themselves (That Open > Select recipe, Update) — Step 6 of that same guide.

> **Making another application talk to this one?** If the user wants their own tool — Rhino, Blender,
> a script, an in-house app — to publish its data so recipes can read it, to updates in its
> own models, or to show a model it did not author, that is a third thing again:
> **[Writing a flow plugin](https://raw.githubusercontent.com/ThatOpen/platform_services/main/docs/flow-plugin-guide.md)** is the
> byte contract, and **[the architecture notes](https://raw.githubusercontent.com/ThatOpen/platform_services/main/docs/flow-architecture.md)** say why it is shaped that
> way. Start at its section 0, which sorts the work into three sizes.
>
> Phrases that mean those: *"export my model to the platform"*, *"write a plugin for X"*, *"read a
> .frag in my app"*.

> **Making a recipe?** If the user wants to bring something of their project into Revit — *"put a
> column at every point of this layer"*, *"build this IFC's walls in Revit"*, *"send my geometry to
> Revit"*, *"a recipe that…"* — that is a recipe, not an app: **[Writing a recipe](https://raw.githubusercontent.com/ThatOpen/platform_services/main/docs/recipes-guide.md)**.
> It is applied from inside Revit (That Open > Select recipe, Update) and saved in their project.

---

## First — what are you building? (ask if the user hasn't said)

There are two kinds of project. **If the user hasn't told you which they want, ASK them
before scaffolding** — explain it in plain terms and let them pick:

- **App** — something people *open and click around in*, running in the platform's browser
  UI: a 3D BIM viewer, a dashboard, a form, a custom tool. Choose this when the goal is a
  visual interface. Template: `app`.
- **Cloud component** — *server-side logic* with no UI of its own, running in the platform's
  cloud and triggered by an app or an automation to do work on the project's data — e.g.
  convert a file (IFC→fragments, point cloud→tiles), generate a report, run a calculation.
  Choose this when the goal is processing/automation, not a screen. Template: `cloud-component`.

Steps 0–2 are identical for both; they diverge only at `create` (step 3) and how you run them
(step 4). This guide marks **[app]** / **[component]** where they differ.

## 0. Prerequisites (check, don't assume)

- **Node.js ≥ 18** and **npm** — verify with `node -v`.
- A **That Open Platform API token**. The user creates it themselves:
  → **https://platform.thatopen.com/dashboard/data → API Tokens → Add → copy.**
  (Account Settings — avatar menu → Account Settings → API Tokens — shows the same card.)
  Ask the user to paste it. **Never print it back, never write it into a file, never commit it.**

## 1. Install the CLI

```bash
npm install -g @thatopen/services@latest
```

## 2. Log in (do this BEFORE creating the project)

Get the token from the platform dashboard — **https://platform.thatopen.com/dashboard**
→ **Data → API Tokens** → Add → copy (Account Settings shows the same card). Ask the
user to paste it, then run:

```bash
thatopen login --token <platform-token>
```

**[Logging in to That Open Platform](https://raw.githubusercontent.com/ThatOpen/platform_services/main/docs/platform-token.md)** is the short version of everything that
goes wrong here: production and dev are separate worlds, `login` does not say which one it saved,
and a machine that is already logged in is somebody's previous session rather than a decision. Read
it if the user is not on a fresh machine, or if anything comes back `Unauthorized` or `403`.

This validates the token and stores it in `~/.thatopen/config.json`. Login **must** come
first: the next step's install pulls the private `@thatopen-platform/*-beta` packages, and
`create` uses your logged-in token to write an authenticated `.npmrc` so that install can
resolve them. No npm account or manual npm token is involved.

### The two credentials, side by side (misusing them is the classic first failure)

| | **Platform API token** | **User session JWT** |
|---|---|---|
| Where it comes from | Dashboard → Data → API Tokens | The platform session (Auth0); inside an app, `PlatformClient.fromPlatformContext()` |
| Lifetime | Long-lived until revoked | Hours |
| Client | `EngineServicesClient` | `PlatformClient` (extends the other, so it can do both) |
| Can | Files, folders, versions, components, executions — anything with an explicit `projectId` | All of that **plus** the JWT-only routes: `listProjects`, `getProject`, `getProjectData`, `checkPermission`, notifications |
| Cannot | The JWT-only routes above — they identify a *person*, a token identifies a *token* | Run unattended: it expires with the session |
| How it travels | `Authorization: Bearer` (the CLI does this for you); the `?accessToken=` query form is legacy | `Authorization: Bearer` |

The failure mode this table prevents: building a service on an API token and discovering
that `checkPermission` or `listProjects` answers 401 — not because of a bug, but because
those questions are only answerable about a person. If a feature needs them unattended,
that is a platform gap to report, not a header to keep fiddling with.

## 3. Scaffold a beta project

**[app]**
```bash
thatopen create my-app --beta
cd my-app
```

**[app, showing a Revit model's commit history]** If what they asked for is a viewer of the
revit-flow history, scaffold it directly. Do not build it by hand: the wiring is four additions in
three places and the ORDER of them is load-bearing (see the boot order section below). This ships
it already correct, opening on the History layout.

```bash
thatopen create my-app --beta --history
cd my-app
```

**[component]**
```bash
thatopen create my-component -t cloud-component --beta
cd my-component
```

`--beta` is required for now (the templates use engine APIs that currently live only in the
beta libraries; public support lands with the October release). `create` configures private
beta access from your platform token and runs `npm install` for you. The **app** scaffold is
a complete working viewer; the **cloud-component** scaffold is a `main()` entry point plus a
`declarations.json` (the parameters the component accepts) — read its `README.md`, which
explains the exactly-four globals the cloud engine injects (do NOT import them) and how to
read/write the project's data.

## 4. Run it

**[app]**
```bash
npm run dev
```
Serves the app and opens it inside the platform. **You now have a complete, working viewer** —
model loading, spatial tree, properties, measurement, sectioning, and more.

If it does not open by itself, or the user closes the tab, the app you are serving from this
machine lives at:

```
https://platform.thatopen.com/dashboard/projects/<PROJECT_ID>/apps/local-app
```

> **If the platform shows "failed to load application" and the console says
> `Permission was denied for this request to access the `loopback` address space`**:
> current Chrome blocks an https page from fetching `http://localhost` until the
> user grants the **Local network access** permission. Tell the user: click the
> icon left of the URL → Site settings → **Local network access** → **Allow**,
> then reload. One-time, per browser profile. Verified 2026-09-22 — without the
> grant the dev loop does not work at all; with it, everything below does.

Substitute the project id. That is the local app running inside the platform's own UI, against
the project's real data. Send the user there rather than to a bare localhost port, which is the
app without the platform around it.

> **`npx tsc --noEmit` reports errors in a fresh beta scaffold, and they are not real.** You will see
> a handful of `Cannot find module '@thatopen/components'` and friends. A beta project aliases those
> imports to the `@thatopen-platform/*-beta` packages in `vite.config.js`, which bare `tsc` does not
> read — so it is looking for packages this project deliberately does not install.
>
> **In this project, `tsc` is not a signal.** Do not try to fix those errors, do not report them as
> problems you found, and do not use a clean `tsc` as your definition of done. `npm run dev` and
> `npm run build` are the ones that tell you anything; to check that something you added really
> shipped, grep the built bundle for it.

**[component]**
```bash
npm run run        # executes the component locally against the platform (no browser)
```
Runs `main()` in a local emulation of the cloud engine so you can iterate before publishing.

## THE BOOT ORDER. Read this before you write a line of an app.

**This is where apps break, and the error never names the real cause.** An app boots in four
stages, and a built-in that touches models or the 3D scene must be initialised in the LAST one.
Call it where it reads naturally, right after `client.setup`, and you get:

```
Error: FragmentsManager not initialized. Call init() first.
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onHighlight')
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onClear')
```

None of which says "you called this too early". The app renders, the panel mounts, and it sits
there inert.

**Why.** `FragmentsManager` is initialised inside `top-app`'s own `setup` callback, and the 3D
world does not exist until `<top-app>` has been added to the DOM and `top-viewer` has built it.
Both of those happen well after `client.setup` returns. Any manager that reads model files or
colours elements reaches for them the moment it starts.

**The order, and it is not negotiable:**

1. `client.setup(...)` with every built-in you need, then `components.get(UIManager).init()`
2. `app.setup = ...`, which is where `FragmentsManager.init` goes, and append `<top-app>`
3. `await firstWorld(...)`, so the world exists
4. **only now**, `init(client)` on the model-facing managers

Copy this skeleton. It is the boot of an app that works.

```ts
async function main() {
  const client = PlatformClient.fromPlatformContext();

  // 1 ── built-ins registered, UI shell up. This is the FULL globals set a
  //      built-in may ask for: OBC, OBF, BUI, THREE, FRAGS, MARKERJS (plus
  //      CUI only if your app still uses the deprecated @thatopen/ui-obc).
  //      Only OBC and BUI are strictly required, but a built-in that needs
  //      a missing one fails at init, so pass everything you import.
  const { components } = await client.setup<OBC.Components>(
    { OBC, OBF, BUI, THREE, FRAGS, MARKERJS },
    { uuid: UIManager.uuid },
    { uuid: GitHistoryManager.uuid },        // and any other built-in you use
  );
  components.get(UIManager).init();

  const viewerEl = document.createElement("top-viewer");
  const app = document.createElement("top-app") as any;

  // 2 ── this callback is what initialises FragmentsManager. Nothing that needs
  //      fragments may run before it has resolved.
  app.setup = (waitUntil: (p: Promise<void>, label?: string) => void) => {
    waitUntil(
      (async () => {
        const fragments = components.get(OBC.FragmentsManager);
        const workerUrl = await FRAGS.FragmentsModels.getWorker();
        fragments.init(await FRAGS.toClassicWorker(workerUrl), { classicWorker: true });
      })(),
      "Fragments Core",
    );
    return { components, client };
  };

  app.elements = { viewer: () => BUI.html`${viewerEl}` };
  app.layouts = { Main: { template: `"viewer" 1fr / 1fr` } };
  app.layout = "Main";
  (document.getElementById("that-open-app") ?? document.body).appendChild(app);

  // 3 ── the world is created asynchronously by top-viewer. Wait for it.
  await firstWorld(components.get(OBC.Worlds));

  // 4 ── ONLY NOW. Everything above had to have happened first.
  await components.get(GitHistoryManager).init(client);

  // ...and from here, the real layouts, panels and elements.
}

/** Resolves with the first world once it exists (top-viewer creates it async). */
function firstWorld(worlds: any): Promise<any> {
  const existing = [...worlds.list.values()][0];
  if (existing) return Promise.resolve(existing);
  return new Promise((resolve) => {
    const handler = ({ value }: any) => {
      worlds.list.onItemSet.remove(handler);
      resolve(value);
    };
    worlds.list.onItemSet.add(handler);
  });
}
```

**Two more traps in the same family:**

- **One stable `top-viewer` node, held in a variable and returned by reference** from every
  `elements.viewer()` call. Creating a fresh element on each render disposes the world and
  builds another one, and everything wired to the old one goes quiet.
- **Registering a built-in is not the same as initialising it.** `client.setup` makes
  `<top-git-history>` resolvable; `init(client)` is what fills it. A panel that mounts and stays
  empty is usually the second one missing, not the first.

## 5. Then build — read the in-project agent guide

The scaffold is real, working code — a complete viewer **[app]** or a runnable `main()`
**[component]** — not a blank page. **Before changing anything**, open and follow:

```
node_modules/@thatopen/services/resources/AGENTS.md
```

(The scaffolded project's own `AGENTS.md` points here too.) It is the canonical guide for
**both** project types: it indexes every platform built-in, the client API, the CLI, and the
engine / UI example sets. Load those indexes before writing code. For an **app**, **all UI
must be built with Lit + `@thatopen/ui` (`BUI`)** — consult the design system first. Run the
scaffold first, then extend it; don't rebuild from scratch.

## 5b. The channel: drive the running app from outside, and multiplayer

The scaffold is already listening. `src/setups/channel.ts` joins the platform
channel at boot with two typed commands (`ping`, `get-loaded-models`), and a
collaboration room shared by every open tab of the app. This is the bridge for
"an LLM on the desktop drives the app" and for multiplayer, and it is the same
system: the platform relays messages between app tabs and external tools.

To command the app from outside (a script, an MCP server, your own tool):

1. The user creates a **platform token** (dashboard → Data → API Tokens). Same
   secrecy rules as always. The token itself needs no special permission: what
   the channel checks is the token owner's role in the project, which must allow
   **API calls**. Project Admin and Member have it by default; a custom role
   needs it ticked.
2. Connect with `socket.io-client` and subscribe, then publish:

```bash
npm i socket.io-client   # in the external tool's own project, not the app
```

```js
import { io } from "socket.io-client";

// WebSocket-only matters: the default long-polling handshake spreads several
// HTTP requests across the platform's load-balanced instances and can die
// before it upgrades. The token rides the auth payload, not the URL.
const socket = io("https://platform.thatopen.com", {
  transports: ["websocket"],
  auth: { accessToken: process.env.THATOPEN_TOKEN },
});
// While iterating with `thatopen serve`, OMIT appId (the dev channel is keyed
// to the account); pass the appId once the app is published.
socket.emit("channelSubscribe", { projectId, appId, kind: "cli" });
socket.on("channelMessage", (msg) => {
  if (msg.type === "channel:subscribed") {
    socket.emit(
      "channelPublish",
      { type: "ping", requestId: crypto.randomUUID(), payload: { echo: "hi" } },
      (ack) => console.log(ack), // { delivered: 0 } = no app tab is listening
    );
  } else {
    console.log("app says:", msg);
  }
});
```

A reply to your `requestId` reaches only your socket — a second tool connected
at the same time never sees it. Replies arrive as a `channelMessage` with
`type: "reply"` and your `requestId` — match on the `requestId`, not the type.

`{ delivered: 0 }` on the ack means no tab of that account's app has the
channel joined — usually the app is simply not open. Apps scaffolded before
services 0.16.1 had one more way here: they joined the channel only at the END
of boot, so a stalled startup request left an app that looked healthy but had
never joined, with nothing in the console either way (0.16.1 scaffolds join
before anything boot can stall on). With the app visibly open and still
`delivered: 0`, **ask the user to reload the app tab and retry**.

To grow the app's command surface, extend `AppCommands` in
`src/setups/channel.ts` and handle the new command — the handler's return value
is the reply. The full walkthrough (typed contracts, collaboration events,
presence) is `node_modules/@thatopen/services/src/core/examples/channel.ts`,
indexed in the client API index you already loaded.

## 5c. Documents: every document is a folder

A DOCUMENT is the platform's unit of content — what a person sees as one file
in the CDE. It is stored as a FOLDER holding its actual files plus a
`document.json` descriptor (schema `thatopen/document@1`):

```json
{
  "schema": "thatopen/document@1",
  "name": "Clinic building",
  "native": { "fileId": "<id>", "format": "rvt" },
  "views": [{ "fileId": "<id>", "format": "frag" }]
}
```

`name` is the document's own name (what a row shows), `native` its native form
(optional — a document born on the platform may have none), `views` its
renderable representations, by fileId so renames do not break them. The ONE
viewer rule: a document is READY TO VISUALIZE when it has a view in a format
the viewer renders; otherwise the interface offers to PROCESS it, and the
processor's last act is `addView`. A format that views itself (a PDF) lists
the same fileId as `native` and as a view — nothing is ever deduced from
extensions. The folder is an internal detail: interfaces show one row and
apply move/rename/delete/permissions to the whole document. Plain files
uploaded outside this shape still work, with fewer abilities (`descriptor()`
returns null).

```ts
const documents = client.documents(projectId);
const all = await documents.list();                       // every document (folderId + descriptor)
const descriptor = await documents.descriptor(folderId);  // null on a plain folder
const view = await documents.view(folderId, ['frag', 'ifc']); // your preference order wins
await documents.addView(folderId, { fileId, format: 'frag' }); // a processor's last act
const doc = await documents.fromFile(fileId);             // convert a loose file into a document
```

`fromFile` creates the folder next to the file, moves the file in (ids survive
moves), and writes the descriptor: the file as `native`, and as `views[0]` too
when its format views itself (`SELF_VIEWING_FORMATS`; `selfView` overrides). A
file with an old `derivedFileId` link (an IFC's frag) brings the derivative
into the folder as a view, so the document is born ready to visualize.

## 5d. History and recipes: versions, bringing data in

Three sentences hold the whole model. Every connected document (a Revit model,
an AutoCAD drawing) has its version history: who synced, when, what changed,
and — when a recipe made it — which recipe and which source. Nobody writes in
somebody else's document: the person working in the native application brings
things in themselves. A RECIPE brings something of the project (an IFC, a Rhino
layer, a .frag) into a native application; it is chosen and applied from inside
that application (in Revit: That Open > Select recipe, Update), and its
changes land there at once, in one undoable step.

```ts
const history = client.history(projectId);
const docs = await history.docs();                 // the connected documents
const doc = history.doc('revit', docs[0].docId);
const timeline = await doc.timeline();             // versions, oldest first
const last = await doc.latest();
// last.kind: 'upload' | 'sync' | 'recipe'; on a recipe step, last.origin says
// { recipe, recipeVersion?, title, source: { folderId, fileId, name, version } }
const holders = await doc.ownership();             // who holds which elements
const view = await doc.view(['frag']);             // same rule as any document

const recipes = await client.recipes.catalog(projectId, { to: 'revit' }); // built-ins + the project's own
const sources = await client.recipes.choices('ifc-to-revit', projectId);  // documents it can read
```

`docs()` also answers `folderId` — the id the CDE knows that document by, the
bridge between this section and 5c.

`client.recipes.run(name, { projectId, target, input, settings, made, opId,
recipeVersion?, progress })` answers `{ title, verb, payload, targets,
ruleTallies }`, or throws `UpToDate` when there is nothing to write. It is what
the native plugin calls on Update; the plugin then writes `payload`
itself. An app does not updates: it can run one to SEE what it would
write — `describeChanges(payload)` lists the changes — and nothing is stored.

To READ a .frag's data without rendering anything, `readFrag(bytes)` answers
its metadata and items (guids, categories, attributes). It and the recipes'
`OperationBuilder` need the optional peers `flatbuffers` and
`@thatopen/fragments` resolvable (loaded only when they run — nothing else in
the package needs them; in plain Node, fragments also pulls `web-ifc`).

BUILT-IN RECIPES ship with the SDK — proof that interoperability works
without writing anything, and the templates to copy:
`registerBuiltinRecipes(client)` registers `rhino-to-revit` (a Rhino layer's
placed objects become instances of a chosen Revit type, reconciled on re-run),
`ifc-to-revit` and `frag-to-revit` (a whole building from the platform's own
records: levels, walls, curtain walls, floors, roofs, ceilings, stairs,
columns). A project's OWN recipes are saved in the project, versioned
(`client.recipes.project.save / versions / source / load / list`), and are
written by a person with an AI: that is
**[Writing a recipe](https://raw.githubusercontent.com/ThatOpen/platform_services/main/docs/recipes-guide.md)**.

This surface is the only supported way in: the storage underneath is private
and will move. Never list or write the `bimterop` files directly. The full
walkthrough (StaleHistoryError on concurrent syncs, the version fields) is
`node_modules/@thatopen/services/src/core/examples/history.ts`, indexed in
the client API index you already loaded.

## 5e. The desktop MCP server: `thatopen mcp`

The raw socket above is for tools you write. For an LLM on the desktop (Claude
Desktop, Claude Code, anything that speaks MCP), the CLI ships the same bridge
as a ready-made MCP server over stdio:

```json
{
  "mcpServers": {
    "thatopen-platform": {
      "command": "npx",
      "args": ["-y", "@thatopen/services", "mcp"]
    }
  }
}
```

Credentials come from `thatopen login` (`~/.thatopen/config.json`); to inject
them instead, set `THATOPEN_TOKEN` and `THATOPEN_API_URL` in the server's
`env`. Two tools: `platform-status` (can the platform be reached, is the
subscription alive) and `send-app-command` (publish a command to a running
app — `ping`, `get-loaded-models`, or whatever the app declares — and return
its reply). The project is named per call, by id or dashboard URL, so one MCP
session can drive whichever project the user has open; while iterating with
`thatopen serve`, `app_id` is omitted, same rule as the raw socket. A dashboard
URL with `/apps/<id>` in it gives the `app_id` as well, so the URL of the
user's app tab is all a call needs. To use an app rather than build one, send
it `help` first (see the box at the top of this guide).

## 6. Publish (when ready)

```bash
npm run publish
```

Builds, zips (`dist/bundle.zip`), and uploads a new version to the platform — for an **app**
or a **component** (a component also ships its `declarations.json`). Re-run it any time to
push a new version.

Once published, it shows up at **https://platform.thatopen.com/dashboard/data** — an **app**
under **Apps**, a **cloud component** under **Components**. Either way it isn't running
anywhere yet: to actually use it, **add it to one of your projects** from there. (A cloud
component, once added to a project, is then triggered by an app or an automation in it.)

---

## Rules for you, the assistant

- **Platform token only.** Never introduce, request, or store an npm token.
- **Never echo or persist the user's token.** It belongs only in `~/.thatopen/config.json` /
  `.npmrc`, both of which the CLI manages and git-ignores.
- **Do the thing they asked for.** If the request already says what to build, build it. Proposing a
  four-point plan and waiting for approval to do what was just requested costs the user a whole turn
  and buys nothing. Stop and ask only when you are about to change files you did not create, when
  the request can be read two ways that mean different work, or when the next step is destructive.
- **Never save to the platform on every change.** Drafts live in memory — the
  production sandbox runs apps on an opaque origin where `localStorage`,
  `sessionStorage`, IndexedDB and cookies all **throw** (they work in dev mode
  and then break for every real user). The platform gets an explicit save. Writes are capped at 30 per minute and a
  `429` loses the write. See
  `node_modules/@thatopen/services/docs/rate-limits.md` before you write any save, sync or
  polling code.
- The scaffold already works — **extend it, don't replace it.**
