# Build a Display

A Display renders an interface in an isolated frame. It declares configuration, data slots, action slots and events; it receives only the data and operations mapped through Flip's scoped bridge. Arrange whole published instances in Canvas Studio. Dragging or resizing does not grant an action permission or alter record schemas.

## Configure an existing component

Read its exact library version and configuration/binding schemas. Read the owned definition, revision and collections, then choose compatible values or owned data. Preserve existing instance identities, settings and pins when making an unrelated edit. Validate the complete definition, save it and explicitly save a named version if requested.

Preview is read-only. It does not authorize record mutations, private file picking, write actions or automation. A shared board is also a view-only context with narrower reads, not an owner grant.

## Author sandbox source

Get the current full package example and contracts with `flip_plugin_authoring_info`. JavaScript, TypeScript and TSX can compile with the fixed React imports and relative package modules; there are no arbitrary npm installs or author lifecycle/build scripts. Source Display artifacts declare `static-bundle`; Flip generates the immutable `index.html` entrypoint and digests.

Export `default mount(root, flip)`. The host invokes it after initialization. There is no extra `flip.ready` promise. The bridge exposes `flip.context`, `flip.onUpdate(callback)`, `flip.request(payload)`, `flip.resize(height)` and declared `flip.emit(...)` messages. Return a cleanup function when needed.

A scoped query uses the existing bridge payload:

```js
const result = await flip.request({
  method: "store.request",
  bindingId: "entries",
  operation: "records.query",
  input: {limit: 50}
});
```

This requires an actual declared binding named `entries` and current host permission. It is not a direct database request. Include the original idempotency key in the normative payload for mutations; never manufacture a new key after an unknown write.

## Pick and download private attachments

A file binding needs its declared `files.pick` and/or `files.read` permissions. `flip.request({method:"files.pick",bindingId:"attachment",idempotencyKey:crypto.randomUUID(),accept:["application/pdf"]})` opens the trusted chooser and returns only a finalized `{fileId}`. Omit `accept` to keep the image-only default. Types must satisfy the actual immutable Store policy; Store1.0.2 adds PDF, macro-free Office files and UTF-8 text within25MiB/200files/1GiB. Existing provider pins remain unchanged.

For a document, request `{method:"files.download",bindingId:"attachment",fileId}`. Current owned Use authority and the existing `files.read` permission are required. Core opens a manual download dialog; the guest receives only `{fileId,opened:true}`, which means the dialog opened, not that the file downloaded. Do not put document bytes in an iframe/object/HTML or ask for sandbox download/pop-up privileges. Images retain the existing preview path. Source3 compiler builds retain file-picker requests for310seconds around the host’s300-second deadline; other requests remain30seconds and all original-key/disposal rules apply.

## Look up editable nutrition references

Use the fixed `nutrition.lookup` host control only after an explicit user action in an owned Use view. Declare `{permissionId:"nutrition",kind:"service",resource:"service:nutrition",operations:["nutrition.lookup"],reason:"Look up food reference facts."}`, reference that permission in the Display and declare a value slot `{id:"nutrition",kind:"value",schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"null"}}`. Bind its saved instance value to `null`. Check current `permissions.services` before dispatch and after awaiting; Preview/shared/public demo contexts have none.

`flip.request({method:"nutrition.lookup",bindingId:"nutrition",input:{query:"banana"}})` searches the complete frozen USDA SR Legacy corpus locally. Use `{barcode:"3017620422003"}` for a validated GTIN read from fixed Open Food Facts; there is no arbitrary URL/network API. Check the app-owned saved-food cache first. The person's Scan barcode or Add food action may continue automatically to one external barcode lookup on a cache miss and open the facts/portion editor; no second lookup button or confirmation is required. Do not send private journal content or retry automatically. Results contain at most five foods plus attribution, all seven facts per100g with unknowns as `null`, gram portions when known and source URLs. Never treat100ml as100g. Show attribution, review/edit facts and portion, then save with ordinary Store operations. Food save and entry creation are separate original-key writes; copy facts into a journal snapshot and disclose partial success. Lookup itself is not a new MCP tool or a Run effect.

## Scan retail barcodes through Flip

Declare `{permissionId:"barcode",kind:"device",resource:"camera:barcode",operations:["camera.scan"],reason:"Scan a retail barcode in Flip’s trusted dialog."}` and include that permission in the Display. Add the value slot `{id:"barcode",kind:"value",schema:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"null"}}` and bind its value to `null`. In the current owned Use view, `permissions.devices` describes the `barcode` slot and its `camera.scan` method; Preview, shared views and public memory demos do not receive it.

An explicit `flip.request({method:"camera.scan",bindingId:"barcode"})` opens Core’s scanner. On the website, the person chooses **Start camera**, enters digits manually or cancels, then confirms **Use barcode**. Opening the web dialog alone never requests a camera. The browser's `BarcodeDetector` is used when its retail formats are supported, with an exact pinned, self-hosted JavaScript ZXing fallback when needed. No remote decoder, upload, WASM or worker is used. Results are only `{barcode,format}`: valid EAN-8, EAN-13 or UPC-A digits, with leading zeros kept. Camera-decoded UPC-E expands to validated UPC-A before return. The generic scanner’s manual field accepts EAN-8, UPC-A and EAN-13; an app can separately accept GTIN-14 manual lookup.

On iPhone 0.3.1 and later, an explicit native **Scan barcode** action opens the trusted scanner and starts video capture after permission is granted, without another Start camera tap. iPhone0.5.3(22) returns the first valid camera-recognized barcode immediately and closes capture, without **Use barcode**. Installed earlier builds still require that confirmation until updated. Manually typed digits keep an explicit submit button so a valid shorter prefix cannot submit before typing is finished. Startup, appearance and interval actions cannot start camera or file controls. Backgrounding or interruption stops capture; returning never resumes it automatically. The website keeps the scanner flow described above.

The guest never receives images, audio, streams or a camera API. Core stops tracks when a barcode is found, the person stops/cancels, the page hides or the view/permission retires; late camera/detection results cannot populate a replacement view. Current server context is checked before opening and before returning digits. The scan operation itself does not look up or save food. Its app-authored continuation may query the saved-food cache, look up an unknown code and open an editable review in the same action. Saving remains a deliberate app action. Source4 builds give `camera.scan` a finite310-second guest deadline around Core’s300-second dialog deadline; `files.pick` retains310seconds and ordinary requests30seconds. There is no automatic scan retry or iframe permission change.


The scanner extension allows `flip.request({method:"camera.scan",bindingId:"barcode",manualEntryLabel:"Add food manually"})`. It shows the requested plain-text button over the native/web camera preview and returns exactly `{manualEntry:true}` if selected, after stopping capture and rechecking current authority. Branch on that marker immediately to open the app's manual form; do not try a barcode lookup or save in that branch. Recognition or manual barcode digits still return `{barcode,format}`, and Cancel remains an error. Labels contain 1–80 Unicode scalars, must not be all whitespace and cannot contain C0 controls or DEL. This is one trusted button, not arbitrary authored camera content. The form and its Save action remain app-owned. In a native/portable action, supply the label through the existing input expression, as shown in the [native contract](../contracts/mobile-display-v1.md#scanner-manual-entry). Requests without the label keep their existing result shape. These options require supporting Core/web software and iPhone0.5.3(22) or later; earlier installed builds reject them until updated.

## Web and mobile compatibility

Classic web Displays use the isolated HTML/JavaScript runtime described here. Native mobile work is separate: choosing or publishing a web Display does not promise native rendering on iPhone. Share ordinary `/app/<UUID>` or `/shared/<UUID>` links. Editing and the complete web experience remain on the website.

To offer a native iPhone interface, add an optional `mobile: {contract: "flip.mobile-display/1.0", artifactId: "native-display"}` descriptor to the classic Display. Declare a separate `static-bundle` artifact and `.json` source entry for it. The [native mobile contract](../contracts/mobile-display-v1.md) defines independently authored screens, tabs, navigation, overlays, native controls and appearance; it does not constrain the web layout. Read the live `flip_plugin_authoring_info.nativeMobile` capabilities and complete example first. The installed instance, configuration and declared data/action slots remain shared. Any additional native action slot must be explicitly declared and mapped to an exact installed Run; the descriptor grants no authority.

Agents can publish additional app interfaces using supported native controls without changing the iPhone binary. New controls or device capabilities require a supported contract/runtime release. Unknown contract versions and controls fail closed. A mobile sibling is part of a new immutable package version; neither building it nor discovering it upgrades an installed app. Preserve existing settings, provider/Run pins and binding identities when deliberately adopting the new version. Web-only Displays remain valid. A supporting iPhone runtime reports a missing mobile interface rather than executing HTML as a native fallback.

Native scrolling lists require iPhone **0.4.0 (16)**; read `nativeMobile.controlRequirements.list` before authoring one. Use `kind: "list"` with `source`, `template`, `emptyText`, optional `key` (default `/id`) and optional `style` (`plain` or `insetGrouped`). Place it at the screen root or directly in its root `stack`, once per screen. Give every item a unique nonblank string key of at most 256 UTF-8 bytes. Keep headers/filters beside the list in that root stack; do not wrap it in `scroll`. Existing row actions use the selected item's context and current permissions. The list displays already-loaded data with the existing 256-row bound; the list itself never queries data, pages, invokes authored actions or writes. Image rows retain existing scoped image loading. Use explicit actions for filtering or additional pages. See the [native contract](../contracts/mobile-display-v1.md) for a complete row example and compatibility behavior.

Native select controls display the authored label beside the current choice. Give each filter a distinct, meaningful label even when several choices begin as All. Native read recovery is implemented by the runtime’s exact event-free/current-authority guards; it does not authorize authors to replay an unknown mutation under a new key.

Portable JSON releases remain immutable and available through exact version history. An explicit `renderer: "portable-v1"` selects that separate renderer; never reinterpret its JSON bundle slot as executable JavaScript. Web discovery prefers the latest classic release when a family has one. Exact existing pins are not silently changed by this default.

## Render current state without extra requests

For richer iPhone design, read the [native design studio](native-design.md). Its local 0.5.0 (19) candidate includes named styles, assets, richer controls and five fictional compositions. `flip_native_design_catalog` and `flip_native_design_validate` provide read-only discovery/static checks; the local `native:preview` command and stdio MCP server provide actual SwiftUI screenshots, interaction and accessibility inspection on a Mac. Use the real renderer feedback loop and inspect light/dark/large-text variants before accepting a design. Building or previewing never upgrades an installed app or publishes it.

Render the bound data in `flip.context.data` at mount and on `flip.onUpdate`. Do not query again on every update; the host already supplies bound state. Keep input controls mounted while updating list/status elements. Adopt a confirmed create/update result, including its revision, into the local view and recompute derived totals. Revalidate only affected data when needed; do not reload every collection after one edit. A failed post-save read means the save succeeded but the display needs to refresh; it is not grounds to repeat that save under a new key.

For native JSON, read `flip_plugin_authoring_info.nativeMobile.performance` and use `flip_native_design_validate` before building. Its additive `performance` report counts authored requests through `onLoad`, each screen's `onAppear`, and `onInterval`. Startup combines `onLoad` with the entry screen's `onAppear`. Minimum/maximum counts conservatively include conditional branches without evaluating them. Warnings identify repeated startup query expressions, long sequential request chains and declared record bindings never consumed through `source:data`. They are advice, not measured latency or a reason to reject a valid filtered query; host binding reads, Run internals, status polling and recovery add work beyond those counts. Validation never invokes a request.

Choose one initial loading strategy for each visible scope. If the host's initial bound page is sufficient, render it directly with `{kind:"get",source:"data",path:"/entries/records"}` as the fictional native source example does. Avoid querying that same scope again in both `onLoad` and entry `onAppear`. A date-filtered screen or later cursor page can need different data; load only that scope and explain the difference. Keep reference data and load history when the person opens it. Do not scan the complete history just to display the next twenty rows.

Native JSON supports bounded local string, object, arithmetic and list expressions, including `map`, `filter` and `sum`. Compute simple derived values from supplied rows locally. A sum of a loaded page is a **loaded-page subtotal**, not a complete collection total when `nextCursor` is present. Use a complete independently verified aggregate when the screen promises a whole-history total. Use Run when its scoped server data or calculation is necessary; a simple local transform does not need a remote preparation action. Native JSON cannot execute arbitrary JavaScript or parallel requests; unsupported calculations need an available runtime capability or Run.

Specify freshness explicitly. Binding refresh replaces `source:data`, so a screen rendered from that source updates with it. Refresh does not rerun arbitrary actions that copied rows into `state`. For state-backed queries, choose an explicit refresh action, screen `onAppear`, or a bounded read-only `onInterval` action and preserve drafts while applying its result. Supported intervals are60–3600seconds; they are polling rather than realtime subscriptions. After a confirmed save, adopt the returned record/revision and update only affected local values before deciding whether another read is required. Preserve original-operation recovery and make partial success visible.

Each frame shares a request bucket across reads, writes, files and Run: burst **8**, refill **32/minute**. Each server context independently allows **32 RPC/minute**; at most **16** bridge requests may be pending. An eight-collection reload immediately after a write already exceeds the burst. Cache reference data, load history only when needed, bound pagination and coalesce overlapping refreshes. A generation check must also stop obsolete pagination from issuing more reads. Preserve the visible view during refresh or throttling and offer a delayed manual retry rather than a tight retry loop.

Well-formed requests refused for quota do not dispatch and do not count as malformed messages. Token refill permits a later explicit request on the same frame/context; there is no automatic retry or new authority. A separate flood cutoff disposes a frame after 64 quota refusals within ten seconds. Malformed/replayed messages retain their separate three-strike protection. For an interrupted mutation, distinguish a known pre-dispatch refusal from an unknown outcome and preserve the exact original input, expected revision and idempotency key for reconciliation.

Native form submission is disabled by the sandbox, including submit-event dispatch. Use ordinary inputs with validated scripted button/Enter handlers. A named `role="form"` can group accessible controls without native submission. Do not request `allow-forms` or relax isolation to make a form submit.

New source frames have opaque origins and a nonce-bound initial message-channel handoff. Parent DOM, session cookies, cloud credentials and direct storage authority are unavailable. Browser source can still see its explicit bindings; inspect shared source before choosing sensitive data. CSP is not a zero-egress guarantee for arbitrary browser code or frame navigation. Declared events never grant downstream automation consent themselves.

Related: [Plugin model](flip://docs/plugin-model), [Store](flip://docs/store), [Source publishing](flip://docs/source-publishing), [Sharing](flip://docs/sharing). Human guide: [Display](https://buildyourflip.com/docs#plugin-model/display).

## Preserve editable intent and confirmed outcomes

A read-only Run that prepares a change must capture the selected record/revision, mode and all editable draft fields. Compare that snapshot before checking its original execution, adopting its result or saving, including edits made before blur. Closing or replacing a draft retires its known preparation; it must not discard an unknown write’s exact original request, key or confirmed prefix. Even synchronous Runs can return queued/running: keep the actual `executionId` and explicitly check that original job.

The Display event API is reserved: current web adapters grant no Display event emission authority. Declaring an event or calling an SDK method cannot enable it.
