Skip to content
Verified

The Studio LLM guide

The prog document model, the xu-* attribute reference, and the workflow rules an AI agent is taught before its first tool call.

Every Studio project, every table, screen, script and route inside it, is one CouchDB JSON document called a prog (docType: "studio"). This page is the same reference an AI agent receives when it builds one, rewritten as documentation: the shape of that document, the attributes that drive its UI, the actions a workflow can take, and the mistakes that show up in real builds.

How an AI agent gets this guide

Connect an MCP client to Xuda and the first response, the initialize call, carries this guide as the session's instructions, merged fresh from the platform's own live rules so it can never describe something the deployed checker no longer enforces. See Connecting an AI client over MCP.

From inside a session, two methods reach the same material directly, over MCP or plain REST, and require nothing beyond a normal API key:

The prescribed order: read the topic that matches what you are building, fetch a matching example, create the prog through the factory (create_prog), build inside its content sections, validate (validate_prog) and fix everything it reports, save (save_prog), then re-fetch to verify. A save that returns -409 means the document changed since it was read: re-fetch, reapply, retry.

The prog document model

The envelope

Server and factory code own these fields; an authored build only ever edits the content sections below them.

json
{
  "_id": "392_cmp_f15654997737",
  "_rev": "3-...",
  "docType": "studio",
  "stat": 3,
  "app_id": "prj...",
  "properties": { "menuType": "component", "menuName": "Orders", "menuTitle": "Orders" },
  "studio_meta": { "created": 1750000000000, "createdByUid": "...", "savedByUid": "...", "parentId": "programs" }
}
  • _id follows <last 3 chars of app_id>_<3-letter type abbreviation>_<12 hex>, for example 392_cmp_... for a component, 392_tbl_... for a table, 392_jvs_... for a javascript prog, 392_gtd_... / 392_std_... for get_data / set_data, 392_fld_... for a folder. The factory generates ids, a build never invents one.
  • stat is 3 for active, 4 for soft-deleted (what deleting a prog sets). Studio's tree only shows stat: 3.
  • properties.menuType is one of globals, table, get_data, set_data, batch, alert, javascript, folder, route, api, component, ai_agent.
  • studio_meta.parentId places the node in the Studio tree: either another prog's id (usually a folder) or one of the type roots, programs (logic and components), database (tables), routes, globals, ai_agents. An unrecognized parentId leaves the node invisible in the tree and is a checker error.

Content sections by menuType

The globals doc

Each project has exactly one global_<app_id> document (menuType: "globals"). Its progFields are readable from every other prog as @field_id. Two system globals ship on every project: @SYS_GLOBAL_OBJ_LOGIN_USER_INFO for the signed-in user, and @SYS_GLOBAL_OBJ_REFS for elements registered with xu-ref. Neither the globals doc nor the tree root can be deleted.

Structural musts

  • properties, properties.menuType, properties.menuName, studio_meta, and studio_meta.parentId are mandatory on every doc.
  • A progFields entry needs a unique id, data.field_id, a data.type of virtual, table, expression or datasource, and a props.fieldType of string, number, boolean, array or object.
  • Reserved runtime variable names, _NULL, _THIS, _FOR_KEY, _FOR_VAL, _ROWNO, _ROWID, _ROWDOC, _KEY, _VAL, are never redefined as field ids.
  • Duplicate ids, unknown menuTypes and malformed sections are all hard errors that validate_prog reports directly.

Expressions and xu-* attributes

Expression syntax

Expressions run against the prog's own dataset. Any field, local, table-bound, global or a parameter, is referenced with @: @search_v, @ORD_Total, @SYS_GLOBAL_OBJ_LOGIN_USER_INFO, plain JavaScript around it, @count_v > 0 ? 'has rows' : 'empty'. An object literal needs wrapping parens, ({ ORD_Status: @status_v }). Inside an xu-for loop, the current item is @_FOR_VAL and its key or index @_FOR_KEY (renameable with xu-for-key / xu-for-val). xu-render and other conditions return the truthy or falsy value directly, never a "Y" / "N" string or an extra comparison.

xu-bind is the one exception

Everywhere else a field is referenced with @. xu-bind takes the bare field id instead: xu-bind="search_v", never xu-bind="@search_v".

The xu attributes

Prefix families

Attribute families that take a suffix. xu-on values are always arrays of handler objects; xu-exp values are always expression strings.

json
"xu-on:click": [{
  "handler": "custom",
  "props": {},
  "workflow": [
    { "id": "1", "data": { "action": "update", "name": { "value": "@saving_v: true" }, "enabled": true }, "props": {} },
    { "id": "2", "data": { "action": "set_data", "name": { "prog": "392_std_...", "properties": {}, "parameters": {} }, "enabled": true }, "props": { "condition": "@form_valid_v" } }
  ]
}]

The value of an xu-on:* attribute is always an array of handler objects, and each workflow is an array of action steps (the full action reference is below, under Logic programs and workflows). A step's props.condition gates it; props.async: true fires it without waiting.

Critical semantics

  • xu-exp:class replaces the static class attribute rather than adding to it. An element carrying both has the static one ignored, so the layout classes belong inside the expression too: xu-exp:class="'card p-4 ' + (@active_v ? 'ring' : '')".
  • xu-script takes a bare function (el) { ... } expression, eval'd and called with the DOM element once the node becomes visible. Guard against re-runs (if (el.__bound) return; el.__bound = true;) and scope every query to el, never to document.
  • xu-style is auto-scoped: every selector is prefixed with the node's [xu-ui-id], so plain element and class selectors stay local and never leak.
  • Neither xu-script nor xu-style values may contain a quote character (' or "), the designer canvas serializes attributes unescaped and one quote corrupts the component. The JavaScript programs section below covers quote-free techniques.
  • Static text belongs in an element's content property. xu-exp:xu-content is for dynamic text only.

Tags

Authoring tags besides plain HTML: xu-template, xu-single-view, xu-multi-view, xu-panel, xu-teleport, xu-slot.

  • xu-single-view scopes a single record (a form root, also usable nested).
  • xu-multi-view repeats its children once per row of the bound data.
  • xu-panel embeds another prog (program attribute plus xu-exp:<param> inputs). Only standard HTML attributes (class, id, style, title, hidden, slot, name, role, tabindex) belong on it besides the param expressions.
  • xu-teleport renders its children at another DOM target (to or xu-exp:to).
  • A capitalized tag name (Button, Card) is a compiled component, not an HTML element, see Embedding below.

Components

A component (menuType: "component") is a UI unit: an element tree (progUi) bound to local state (progFields), optional data (progDataSource), lifecycle logic (progEvents) and an input/output interface (properties.progParams).

Properties

json
{
  "menuType": "component", "menuName": "OrderList",
  "renderType": "form",
  "uiFramework": "@xuda.io/xuda-framework-plugin-tailwind",
  "rwMode": "R",
  "progParams": [{ "id": 1, "data": { "dir": "in", "parameter": "order_id_in", "type": "string" }, "props": {} }]
}
  • renderType is form for a single record (root element xu-single-view) or grid / list for one repeated per data row (root element xu-multi-view).
  • rwMode is R for read or U for update; allowCreate says whether a new row can be inserted when none matches.
  • progParams naming convention: parameters end _in / _out, component-local virtual fields end _v.
  • uiFramework mirrors whatever the project's existing components already use. An existing project that omits it should keep omitting it, setting a framework plugin the project's drive does not actually serve stalls the live preview on a blank screen.

The element tree (progUi)

json
{
  "id": "root", "type": "element", "tagName": "xu-single-view", "attributes": {},
  "children": [
    { "id": "ui-...", "type": "element", "tagName": "div",
      "attributes": { "class": "card", "xu-style": ".card { padding: 16px; border-radius: 12px; }" },
      "children": [
        { "id": "ui-...", "type": "element", "tagName": "h2", "content": "Orders", "attributes": {}, "children": [] },
        { "id": "ui-...", "type": "element", "tagName": "input", "children": [],
          "attributes": { "type": "text", "placeholder": "Search", "xu-bind": "search_v" } }
      ] }
  ]
}

The factory root node stays; a build works inside its children. Every node needs a unique id (new nodes use ui-<uuid>), type: "element", and a tagName, no comment or text node types, static text lives in content instead. Every node needs attributes: {} and children: [] even when empty, the designer canvas serializer dereferences both on every node and an omission breaks the component's own preview.

Embedding: xu-panel or a compiled component

Both mount transparently, no wrapper element, and both are decided by one signal: whether tagName starts with a capital letter.

  • xu-panel, lower-case tagName plus a program attribute, embeds another prog, a database-bound or stateful child with its own fields and events. program is the child's id (or xu-exp:prog for a dynamic one), values reach its _in params through xu-exp:<param>.
  • A capitalized tag plus a library attribute mounts a compiled component, a design-system primitive or a part the app itself compiled. Every plain attribute becomes a prop (props.<name>), never a DOM attribute, since the component renders no element of its own. A component node has no out-params, unlike xu-panel nothing writes a value back to your fields.
Capitalization alone decides

A typo'd <Buton> is still claimed as a component tag, never falls back to an unknown HTML element, and throws at mount naming the tag, the library, and every source tried. validate_prog does not check component tags or library values today, the live preview is the only check.

progFields

json
[
  { "id": "<uuid>", "data": { "type": "virtual", "field_id": "search_v" }, "props": { "fieldType": "string" }, "workflow": [] },
  { "id": "<uuid>", "data": { "type": "table", "field_id": "ORD_Total" }, "props": { "fieldType": "number" }, "workflow": [] }
]

data.type is virtual for local state, table for a column of the bound datasource, or expression / datasource. A field's workflow runs on change. A default sets props.fieldValue; a computed field sets props.fieldComputed: true plus propExpressions.fieldValue.

progDataSource

A single record by key (form): dataSourceFilterModelType: "index" with a dataSourceIndexId that exists on the table's own tableIndexes. A filtered list (grid or list): dataSourceFilterModelType: "query" with filterModelMongoFx, a Mongo-style expression string. dataSourceType is table, array, json, csv, none, or empty for a purely presentational component with no data source at all.

progEvents and the three lifecycle hooks

Event types: on_load, on_exit, before_record, after_record, record_not_found, locate_not_found, screen_ready, on_refresh, on_unload, client_interval, user_defined. user_defined events fire from anywhere with the raise_event action; screen_ready is the usual mount hook.

A component's three built-in hooks split the work, using the wrong one is a common source of bugs:

screen_ready

Fires once per instance. Create DOM and widgets here.

on_refresh

Fires after every load, including the first, right after screen_ready. Hand new data to widgets that already exist. Putting refresh work in screen_ready instead re-runs create code against DOM that still exists and stacks a second widget.

on_unload

Fires when the instance is torn down. Destroy what the prog created, widgets, timers, document / window listeners, observers. The engine can only free what it created, a listener bound to document outlives the panel otherwise.

Patterns

  • Loading and empty states: put xu-ref="myref" on the data-bound element, then gate skeleton or empty elements with xu-render over (@SYS_GLOBAL_OBJ_REFS).myref, its dataset attaches once data arrives.
  • Modals: build the dialog as its own component, open it with the call_modal action.
  • Save or delete a bound row: invoke_action with act_save / act_delete, or a dedicated set_data prog for anything past the current row.

Logic programs and workflows

Logic prog types share a component's data machinery (progDataSource, progFields, progEvents, properties.progParams) without any UI:

Parameters

json
"progParams": [
  { "id": 1, "data": { "dir": "in",  "parameter": "order_id_in", "type": "string" }, "props": {} },
  { "id": 2, "data": { "dir": "out", "parameter": "total_out",   "type": "number" }, "props": {} }
]

A caller passes values through the action's name.parameters, { "order_id_in": { "value": "", "fx": "@selected_id_v" } }, value for a static value, fx for an expression. The checker verifies the target program exists and its menuType matches the action.

Workflow actions

A workflow is an array of steps, { "id": "...", "data": { "action": "...", "name": { ... }, "enabled": true }, "props": {} }, run in order. props.condition gates a step, props.async: true fires it without waiting. Workflows appear in xu-on:* handlers, progEvents[].workflow, and a field's own workflow.

invoke_action accepts act_next, act_prev, act_first, act_last, act_reload, act_refresh, act_print, act_save, act_delete (component context only).

Deprecated actions the checker rejects

alter_ui_element, create_ui_element, info_ui_element, remove_ui_element, empty_ui_element, cache_ui_element, load_ui_element. Drive UI through fields and xu-exp / xu-render instead of an imperative element action.

call_ai_agent and call_triage_agent are not real actions

Studio's own action picker offers Call AI Agent and Call Triage Agent next to the actions above. Neither is in this table because neither is one: validate_prog has no case for them and reports invalid trigger type, and the runtime workflow engine has no handler for them either, so a saved step never runs even if the error is ignored. To have one prog reach a published agent, add an AI Agent tool to another agent's own tool list instead (a menuType: "ai_agent" doc's agentConfig.agent_tools), not a workflow step on a component, get_data, or any other prog type.

update's name.value assigns fields with semicolon-separated @field: expression pairs, or a JSON5 object, "@saving_v: true; @status_v: 'sent'". Calling another program names it under name.prog, matching the action to the program's own type (get_data needs a get_data prog, call_native_javascript a javascript prog, and so on).

call_library calls an installed plugin method: name.plugin_name must be purchased and installed on the app or the checker rejects the step, name.library_method one of the methods the plugin exports, name.library_props its declared fields. Two prop names are a convention across plugins rather than specific to any one of them: event_name_for_successful_callback raises that event with the method's response, field_id_to_return_result writes the response into that field directly, neither is required.

progEvents types

on_load, on_exit, before_record, after_record, record_not_found, locate_not_found, screen_ready, on_refresh, on_unload, client_interval, user_defined. screen_ready is the usual init hook; before_record / after_record / record_not_found / locate_not_found are data lifecycle, especially for set_data and batch; client_interval is a repeating timer; user_defined fires from the raise_event action.

Tables

A table prog (menuType: "table") defines a database table: its columns (tableFields), its indexes (tableIndexes), and the database plugin storing it (properties.databaseSocket). Tree parent: database, or a folder under it.

json
{
  "properties": { "menuType": "table", "menuName": "ORD - Orders", "databaseSocket": "@xuda.io/xuda-dbs-plugin-xuda" },
  "tableFields": [
    { "id": "<uuid>", "data": { "field_id": "ORD_Id" }, "props": { "fieldType": "string", "mandatory": true } }
  ],
  "tableIndexes": [
    { "id": "<uuid>", "data": { "name": "index_1", "unique": true, "keys": ["ORD_Id"] }, "props": {} }
  ]
}
  • databaseSocket must name a database plugin installed on the project, @xuda.io/xuda-dbs-plugin-xuda is the platform default; an existing table in the same project is the reference for which socket to reuse.
  • At least one field and at least one index are required.
  • field_id starts with a letter, then letters, digits, underscore, dash, colon or dot, and stays unique within the table.
  • fieldType is string, number, boolean, array, object or date; mandatory: true makes it required on save.
  • Every index needs a non-empty name and keys, and every key must be an existing field_id.

Convention: prefix columns with a three-letter table code, a table named "ORD - Orders" gets ORD_Id, ORD_Total, ORD_Status. Give every table a unique <TBL>_Id field with a unique index on it, a single-record component binding needs it.

A table is used three ways: a component or query's progDataSource.dataSourceTableId, a get_data / set_data / batch prog for row-level access from workflows, or xu.dbs_create / dbs_read / dbs_update / dbs_delete from a script, covered next.

JavaScript programs

A javascript prog (menuType: "javascript") holds real JS source in scriptData.value, compiled on save. save_prog triggers that build and returns the result as data.compile, { ok: true, dependencies } or { ok: false, error }. A failed compile still saves the doc, so a build reads compile.ok and fixes it before moving on.

The execution contract

The source is written as a plain async body, no export, no wrapper. At run time it executes as:

js
async function (params, xu, SESSION_ID, SESSION_OBJ, jobNoP, $container, func, glb, APP_OBJ, evt) {
  /* source */
}

params are the caller's already-evaluated inputs; xu is the runtime API below; a return value is optional, the idiomatic way to hand results back is xu.set_field_value on the calling component's fields. Quotes are fine here, unlike an xu-script attribute value.

The xu runtime API

js
const raw = await xu.get_field_value(`rows_json_v`);
const rows = typeof raw === `string` ? JSON.parse(raw || `[]`) : raw || [];
for (const row of rows) {
  await xu.dbs_create(`392_tbl_...`, { CNT_Name: row.name || ``, CNT_Email: row.email || `` });
}
// dbs_read resolves to an ARRAY of { id, value } rows: the row id on .id, table fields under .value.
const all = await xu.dbs_read(`392_tbl_...`, {}, [], null, 999);
await xu.set_field_value(`status_v`, `Saved ` + rows.length + ` rows`);

dbs_* methods take the table prog's own _id, never a name. Selectors are Mongo-style objects on the field ids, {} returns everything (default limit 999). The fields projection is optional, [] returns every field and a list of field ids returns only those.

Passing data in: fields, not parameters

call_native_javascript does not evaluate {value, fx} parameter wrappers, name.parameters reaches the script raw. The reliable contract: the component puts the payload in a field first (an update step or an xu-bind input), the workflow calls the prog with empty parameters: {}, and the script reads it with xu.get_field_value and reports back with xu.set_field_value. Calling from another script instead, xu.call_javascript(prog_id, {...}) does pass params directly.

Live-preview quirks

  • Data writes reach the real database, but xu.dbs_read reads a local draft store that may not hold fresh server rows, a read right after a write can come back empty in preview even though the write landed (visible in the table's Data tab in Studio). Deployed apps read and write the same store.
  • Compiled scripts cache hard in dev previews, a running preview can keep executing the previous script even across reloads after a save recompiles it. A hard browser refresh clears it.
  • xu.alert with modal, toast or browser display can surface as a native, blocking alert() in preview. xu.set_field_value into a status field is the safer way to report back.

javascript prog vs xu-script attribute

Quote-free techniques for xu-script / xu-style

The designer canvas serializes attribute values unescaped, so a single quote corrupts the component's markup. Template literals avoid string quotes entirely (el.textContent = `Ready`); the literal " character, for example while building CSV, comes from String.fromCharCode(34); CSS attribute selectors are valid unquoted (el.querySelector(`[data-role=import-btn]`)); and a re-run guard, if (el.__bound) return; el.__bound = true;, keeps a script from double-binding on re-render.

Landmines

Every entry below broke a real build at some point. validate_prog catches most of them, run it before every save.

API mechanics

  • Every response is { code, data }, code < 0 is an error.
  • create_prog returns the new doc under data.prog, saving the whole response instead persists a malformed doc with properties buried under prog.
  • save_prog replaces the whole document. Start from the current doc, never a hand-assembled skeleton; a -409 means it changed since the last read, re-fetch, reapply, retry.
  • Over MCP, prog_json and properties_json are passed as strings, the tool schema layer strips unknown keys from an object parameter and can silently drop whole sections.
  • delete_prog is a soft delete, it sets stat: 4. The global_<app_id> node cannot be deleted.

Doc content

  • No ' or " inside xu-script or xu-style values.
  • $-prefixed keys ($folded, $childrenClass, $nodeBackClass), plus path, code, editCode, are designer view-state and never belong in a saved progUi node.
  • No comment or text node types, elements only, static text in content.
  • Every element node needs attributes: {} and children: [] even when empty.
  • xu-exp:class replaces the static class, every needed class belongs inside the expression.
  • xu-bind is a bare field id, no @, everywhere else fields use @.
  • Only the documented xu-* attributes do anything, an invented one is silently ignored and validate_prog warns.
  • An ai_agent prog's tree root is ai_agents, save it with studio_meta.parentId: "ai_agents" (or a folder id under it) if the checker flags parentId.

Runtime and rendering

  • A capitalized tagName is always claimed as a component, even a typo, and throws at mount naming the tag, the library, and every source tried, there is no silent "does not render" the way an xu-panel with no program selected has.
  • validate_prog does not check component tags or library values, only the live preview catches a misspelt one.
  • No utility CSS (Tailwind or otherwise) at runtime unless the project's uiFramework plugin actually provides it, classes like p-4 silently no-op otherwise. Self-contained styling is xu-style, auto-scoped by [xu-ui-id].
  • xu-script runs once per element visibility and may re-fire on re-render, guard with el.__bound and scope queries to el.

Data and scripts

  • call_native_javascript parameters are not evaluated, pass data through fields instead (see Passing data in, above).
  • dbs_read rows are {id, value}, fields live under .value, the row id on .id. Do not pass a fields projection, it breaks the server-side read.
  • Inside xu-for, wrap the iterator in parens, (@_FOR_VAL).CNT_Name evaluates, @_FOR_VAL.CNT_Name fails silently and renders the substituted source text instead.
  • Preview writes land in the real database; preview reads come from a local draft store that can look empty right after a write.
  • Prefer a status field over xu.alert's modal or toast display in previews, it can render as a native, blocking alert().

Verifying your work

Re-fetch with get_prog after saving and diff what was expected. For UI work, open the component in Studio and press the preview play button, or the project's live-preview URL when one is available. For a javascript prog, check data.compile.ok on every save. Fix every validate_prog error; treat its warnings, quotes, $-keys, unknown attributes, as fix-now items rather than noise.