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:
{
"version": 1,
"entryPath": "src/App.tsx",
"dataset": {
"kind": "dataset",
"datasetPath": "tracker/dataset.json",
"operations": ["listExpenses", "createExpense"]
}
}
Rules:
- Always include
"version": 1and"entryPath"(relative to the app folder, no leading/). inputsis optional. When omitted, dohc discovers the app folder's source files automatically. When provided, every path is relative to the app folder and must includeentryPath.packageMapis optional and defaults to{}.dataset.datasetPathis relative to the workspace root and ends indataset.json.- Use either
operations: ["opName", ...](recommended) oroperationIds: ["<UUID>", ...], never both. OmitrevisionandrevisionSha256soprepareLocal,prepare, andstagepin the latest approved Collection revision automatically. - An app can bind up to 16 Collections using
datasetsinstead ofdataset: an object map"datasets": { "<alias>": { "kind": "dataset", "datasetPath": "...", "operations": [...] } }(callbackend.invokewithdataset: "<alias>"). Apps with more than one Collection get no live updates on a share link. - Only one of
dataset,datasets, orcollectionmay appear. - For typed rows, run
dohc dataset types '{"workspaceId":"...","datasetPath":"..."}'. It writes.dohc/types/<name>-<datasetId>.d.tsfrom the approved revision and returns the exactpath. Import it withimport type { FieldIds, Row, Operations } from "<relative path>/.dohc/types/<name>-<datasetId>"and run it again after each approved change. Give a customactionacontractindataset.jsonto type it withInput<"name">andOutput<"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.jsonrefuses unknown keys. They go in the app folder'sdohc.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-runtimedohc/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 asPlus,Trash2,Receipt, andWallet; unused icons are left out of the bundle)dohc/money(formatCentsandparseCentsfor exact whole-cent amounts) anddohc/csv(parseCsvand formula-safetoCsv)
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/uifor quick internal utilities. Usedohc/uiandAppShellwhen 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
ModalorDateFieldfromdohc/uiwithout usingAppShell. The kit places its:roottokens andhtml, bodydefaults in@layer dohc-kit, so unlayered:rootandbodyrules in your CSS override them regardless of import order. Override--kit-*tokens andcolor-schemein: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:
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, ordocument.cookie. They throwSecurityErrorin 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 Policyconsole.erroreven insidetry/catch, which failsverifyFrontend. ImportcopyText(text)fromdohc/app(or sendhost.copyoverdohc-app-channel) from a click or key handler. - Do not call
window.print()directly inside the app frame. Chromium ignores it withoutallow-modals. Importprint()fromdohc/app(or sendhost.printoverdohc-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 viaallow-downloads. - Call
requestFullscreen()only whendocument.fullscreenEnabledistrue, from a click or key handler. A share link allows full screen; dohc's own tab andverifyFrontenddon't, and there it rejects and logs a Permissions Policyconsole.errorthat failsverifyFrontend. Fill the frame with CSS (height: 100vh). - Give an
IntersectionObserveran explicitroot(documentor the scrolling element) when it usesrootMargin. Without one, the opaque-origin frame ignoresrootMargin, 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, brokendohc-app-channelhandshakes, 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(default10000).
- Use
dohc_test_appfor quick folder detection and entry presence checks; useverifyFrontendto compile and run the frontend end to end against an empty ephemeral Collection.
{
"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:
{ action: "prepareLocal", workspaceId, appRoot }-> returnsapprovalId,candidateDigest.{ action: "approve", workspaceId, approvalId, candidateDigest }-> returnspublicationId.{ action: "launchLocal", workspaceId, publicationId }-> returns a localurlwhile dohc is open.
- Combined app + Collection staging (creates or migrates bound Collections and approves the local app in one review):
{ action: "stage", workspaceId, appRoot, migrations?: { "<datasetPath>": "<migration.sql>" } }-> returnsstage.stageIdandstage.reviewDigest. Omit a Collection's entry frommigrations(or omitmigrations) for operations-only updates without schema SQL changes.{ action: "approveStaged", workspaceId, stageId, reviewDigest }-> applies Collection changes and activates the local app.
- Rolling back a local approval:
{ action: "listLocal", workspaceId, appRoot }-> returnspublications(active approval) and up to 3 earlier approved versions inhistory(newest first).{ 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 returnsapprovalId,candidateDigest. Restoring changes only the approved bundle, not the source files on disk.{ 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
listLocalhistoryto roll back if needed. - For a side-by-side rewrite over the same Collection (for example
Money v3/besideMoney/), create a sibling app folder with its ownapp.publish.jsonpointing at the samedatasetPath. When the new app needs different backend logic, add new Collection operations (for examplecatalogGetV3) rather than mutating operations the existing app depends on. Adding an operation changes the Collection'soperationsSha256, so existing sibling apps still require re-approval (dataset permissionsboundAppsshowsneeds-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.
- Create link:
{ action: "createLink", workspaceId, appRoot, operationId: "<fresh UUID>" }-> returnsshareId,grantId, and one-time bearerurl. Reuse the sameoperationIdon retry. - Prepare:
{ action: "prepare", workspaceId, appRoot, shareId, grantId }-> returnsapprovalId,candidateDigest. - Approve:
{ action: "approve", workspaceId, approvalId, candidateDigest }-> returnspublicationIdandappQuery(?app=<publicationId>). - Append
appQuerybefore 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 (
boundAppsscope: "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 listonly listslinkandworkspacepublications. For apps bound to a Collection, checkdataset permissionsboundAppsforscope: "owner"andstatus: "compatible"(apps without Collection bindings have noboundAppsentry, and phone launch checks approval separately). The owner gets every bound operation (owner,helper, andlink). - 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):- Prepare:
{ action: "prepare", workspaceId, appRoot, audience: "workspace" }-> returnsapprovalId,candidateDigest. OmitshareIdandgrantId. - Approve:
{ action: "approve", workspaceId, approvalId, candidateDigest }-> returnspublicationId. - 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) showssync.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 whenstateis"active"and everycollections[].stateis"ready". Eachmembers[]entry, keyed bymemberIdfromdohc members list, showsopens, areasonwhen it doesn't (outside-app-folder,no-collection-access,app-unavailable), and per Collection theaccessandoperationsthat 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 withpublication_not_readyormember_cannot_openwhen 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 officialkind: "workspace"app and read itsurl. - Call
dohc_publish_app{ action: "list", workspaceId, appRoot }(dohc app list) to inspect activeaudience: "workspace"publications, theirsourceRevision(compare withcheckLocal), and their bounddatasetCapabilities[].operations. - Call
dohc_dataset{ action: "permissions", workspaceId, datasetPath }(dohc dataset permissions) to confirmplace.kind === "server",boundAppsshowsstatus: "compatible", anddefaultsis current (matchingrules.revisionSha256proves defaults are active; compatible revisions such as a Collection rename can also preserve defaults pinned to an earlier approved revision).
- Check
- 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, andlink). - 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 (viewgetsview;commentgetsview+comment;editgetsview+comment+edit) or in their current explicitkind: "data"grant. Evenaccess: "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.
- Owner (on any device signed in as the workspace owner): gets every bound operation in the app (
- Set defaults with
dohc_dataset{ action: "setDefaults", workspaceId, datasetPath, defaults: { view, comment, edit, revision, revisionSha256 } }. Defaults never include owner-only actions, andviewandcommentdefaults are read-only. Takerevision,revisionSha256, and the actions to choose from out ofpermissionsrules. An Admin of a workspace they joined does the same withdohc_collection_access.
- Prepare:
Re-approving apps after a standalone Collection migration
- Inspect
boundAppsreturned byprepareSchemaChange,prepareMigration,prepareRelationChoices,prepareHistoryRestore, ordataset permissions. - Each entry reports
scope("local","link","workspace", or"owner"),appRoot,shareId/grantId(for share links),status("compatible","needs-refresh", or"incompatible"), and plain-Englishreasonswhen incompatible. IfboundAppsIncompleteistrue, checkdataset permissionsafter applying the change. - For
"incompatible"apps, update the app's source orapp.publish.jsonto match the changed actions or fields first. - For older apps whose
app.publish.jsonstill pinsrevisionandrevisionSha256, remove those two fields once. - Re-approve each affected local app with
prepareLocal+approve(orstage+approveStaged), and each affected share-link app withprepare+approveusing itsshareIdandgrantId. Re-publishing a share-link app returns a newappQuery(?app=<newPublicationId>); withdraw the previouspublicationIdexplicitly when ready.