Apps — Building and Testing Mini-Apps
The apps plugin lets an agent publish a static web app or a web app with a
sandboxed Python backend at a stable URL. Viewers sign in through Codumentor;
org means all signed-in users, not anonymous public access.
Agent access and configuration
The built-in build-app skill supplies the workflow; this page is the API
reference. With the product_docs plugin enabled, agents can search it using
codumentor_docs(query="mini-apps"), query="req.storage", or
query="CodumentorApp", then read the returned section ids. Documentation is
not automatically injected, and reading a parent section does not include its
children. The skill explicitly tells agents to load the relevant sections.
Built-in skills require the skills plugin with builtin_enabled: true.
plugins:
- module: codumentor.plugins.apps
class: AppsPlugin
args:
enabled: true
Plugin args: enabled (default true); data_dir (default <data_dir>/apps).
The deployment also needs api.apps.enabled and an app origin. Backend apps
and capability apps require the per-app wildcard origin; capability apps also
require authenticated users. See published-app configuration
for origin, sandbox, resource, storage, and handoff limits. Documentation does
not establish live availability or permissions. App tools are offered to the
main agent only when published apps are enabled.
Authoring workflow and layout
app_create(path, title, description?, app_id?, backend?)scaffolds an app.app_iddefaults to the directory name: 3–48 lowercase letters, digits or hyphens, starting and ending with a letter or digit.- Edit
public/and, if needed,backend/. Use relative asset paths, not site-root paths. Frontend frameworks must produce a static build here; their development server and installed packages are not published. Bundle browser dependencies locally: the published content policy blocks off-origin assets and requests, form submissions and service workers.public/_codumentor/is reserved for the host. - Preview
public/index.htmlwithpreview_app. This is frontend-only: the published backend and/_codumentor/endpoints are not provided there. app_publish(path, app_id?)requests approval, creates an immutable version, and moves the stable URL to it. Return the tool's URL, not a constructed hostname. Publishing an update affects existing viewers.app_checkout(app_id, path, version?)copies the current or specified published version into a directory without an existingapp.yaml. Keepapp_idexplicit on republish if the checkout directory has another name. Earlier versions can be restored from the Apps page.app_logs(app_id, ...)reads backend logs for the owner/admin. Read its live tool schema for available filtering options.
my-app/
app.yaml
public/index.html
public/... # browser assets; all are served to viewers
backend/main.py # optional, sandboxed Python
Only app.yaml, public/ and backend/ are published. Do not put secrets,
source dependency trees, or private data in them. Keep tests outside this tree.
# app.yaml: unknown keys are rejected
title: Personal notes
visibility: private # private | org; default private
entry: index.html # relative to public/; default index.html
backend: backend/main.py # omit for static-only apps
Optional description is text; optional capabilities is described below.
Browser API: CodumentorApp
Load the host-provided browser library on the published page:
<script src="./_codumentor/sdk.js"></script>
<script>
(async () => {
await CodumentorApp.init();
const me = await CodumentorApp.user();
const saved = await CodumentorApp.api("note"); // GET /api/note
console.log(me.username, saved.text);
})().catch(console.error);
</script>
This relative script URL assumes the default top-level index.html. For a
nested entry page, adjust the script path to the app root. The library uses
app-root API URLs regardless of the current page path.
| API | Contract |
|---|---|
await CodumentorApp.init() | Initialize theme and embedded authentication. Call before API requests. Standalone uses the app session cookie; the Codumentor iframe obtains a short-lived bearer from its parent. Do not implement or persist tokens yourself. Initialization alone does not prove authentication; requests can still fail. |
await CodumentorApp.user() | Viewer object: id, username, display_name, email, roles. Display information, not browser-side authorization. |
await CodumentorApp.api("note", options?) | Calls the app's /api/note. options: method, body, headers, raw. Default GET, or POST when a body is supplied; object bodies are JSON-encoded. |
await CodumentorApp.handoff({title, prompt, data}, {newTab: true}?) | Store a handoff and open its Codumentor composer. newTab applies standalone; embedded apps ask the parent to navigate. Returns {url, handoff_id, expires_at}. Requires deployment support. |
CodumentorApp.appId, .framed | Current app id and, after initialization, embedded-mode flag. |
CodumentorApp.applyTheme(vars) | Apply allowed theme variables. CSS variables: --cdm-bg, fg, muted, accent, border, surface, font, radius (each with the --cdm- prefix). |
req.json on the backend is a property, not a function. Browser api() is
not a general fetch options passthrough: only the documented options apply.
api() resolves to parsed JSON for JSON responses, otherwise text (raw: true
returns a browser Response for non-JSON responses). It rejects on non-2xx
with an Error carrying status, error, and error_id when supplied by the
server. Handle loading, empty, denied and failed states explicitly. Use
textContent, not untrusted HTML, when displaying user or integration data.
Backend API: routes, req.user and responses
Backends use the host-supplied codumentor_app Python library, not Flask or
FastAPI. Handlers are synchronous and paths include /api/:
from codumentor_app import HTTPError, route
@route("GET /api/note")
def read_note(req):
return {"text": req.storage.user.get("note", "")}
@route("POST /api/note")
def save_note(req):
data = req.json
if not isinstance(data, dict) or not isinstance(data.get("text"), str):
raise HTTPError(400, "text must be a string")
if len(data["text"]) > 10000:
raise HTTPError(400, "note is too long")
req.storage.user.set("note", data["text"])
return {"text": data["text"]}
From the browser, save with
await CodumentorApp.api("note", {body: {text: "Hello"}}).
| Request member | Meaning |
|---|---|
req.method, req.path | HTTP method and app-relative path, such as /api/note. |
req.params | Path captures, e.g. @route("GET /api/items/{id}") → req.params["id"]. |
req.query | Dictionary of first query-string values; req.query_list(name) gets all values. |
req.headers | Forwarded, filtered request headers; not the viewer's session credentials. |
req.body, req.text, req.json | Bytes, decoded text, parsed JSON. Empty JSON body gives None; invalid JSON raises HTTP 400. Validate types and allowed values yourself. |
req.user | Host-verified viewer: .id, .username, .display_name, .email, .roles (tuple), .to_dict(). Never trust a submitted user id instead. |
req.app | .id and immutable dispatched .version. |
req.storage | Shared and per-viewer JSON key-value storage; see next section. |
req.handoff(...) | When enabled, creates a descriptor, not a conversation; see handoff below. |
req.capabilities | Brokered integration access when declared; see capabilities below. |
Route methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, or ANY. A GET
handler also matches HEAD. Return a dict/list for JSON, str for text, bytes
for binary, or None for HTTP 204. For explicit status/headers use
Response(status=201, headers={}, body={"created": True}) imported from
codumentor_app; response headers are filtered by the host. Raise
HTTPError(status, message) for a safe viewer-visible error. Unexpected
exceptions become generic 500 responses with an error_id; inspect app_logs
for the traceback. Do not expose secrets in errors or logs.
Storage API: req.storage.user and req.storage.app
Both namespaces have the same methods:
| Method | Result |
|---|---|
get(key, default=None) | JSON value or default if absent. |
set(key, value) | Store a JSON-serializable value. |
delete(key) | Boolean: whether a key was removed. |
keys(prefix="") | Sorted matching keys. |
items(prefix="") | Iterator of matching (key, value) pairs. |
Keys are nonempty strings, at most 512 characters. req.storage.user is the
current viewer's namespace; req.storage.app is intentionally shared by all
viewers of this app. The namespace separation is enforced by this API, **not
by a separate filesystem sandbox per viewer**: backend code can access the
app's whole data directory. Do not accept raw file paths or expose other
viewers' data through your own endpoints.
Data lives under /data and survives worker recycling and republishing;
deleting the app deletes its data. Over quota, set raises
StorageQuotaExceeded (from codumentor_app); reads and deletes remain
available. Multiple workers may run: globals are shared with other viewers
within one worker, are not durable, and are not consistent across workers.
A get followed by set is not an atomic increment or transaction.
Sandbox and capabilities: req.capabilities
The published backend is standard-library-only Python, with no direct
network, repository, instance configuration or host-secret access. /app
and /sdk are read-only; /data is durable writable app storage and /tmp
is temporary. Requests have deployment-configured time, memory and size
limits. Do not start a server, spawn background jobs, install packages, or
use a development server as the published runtime.
Integration access must go through declared host capabilities, not browser
credentials or backend network calls. The concrete convenience method is a
read-only database query:
# Add to app.yaml only after verifying this connection is available:
capabilities:
- kind: db.query
connection: sales
result = req.capabilities.db_query(
"sales", "SELECT id, total FROM orders WHERE id = ?", [7], limit=100,
)
# {"columns": [...], "rows": [[...]], "row_count": n, "truncated": bool}
The connection name and parameter syntax depend on the configured database;
sales and ? are examples, not guaranteed deployment resources. Use bound
parameters, never interpolate user input. A lower-level
req.capabilities.call(kind, constraints, params) exists for capabilities
actually supplied by installed plugins; do not invent supported kinds.
The host validates declarations on publish and checks the viewer's grant,
permissions, deployment policy and limits on each call. A viewer may decline
or revoke consent; growing the capability set asks again. Handle denial, do
not bypass it. CapabilityError (from codumentor_app.capabilities) exposes
code, message, reason; uncaught it becomes a structured HTTP error.
Conversation handoff
When enabled, req.handoff(title="...", prompt="...", data={...}) returns a
descriptor that the frontend can pass to CodumentorApp.handoff(descriptor).
The frontend can also construct {title, prompt, data} itself. Use JSON data,
include only what the viewer should share, and keep within deployment limits.
This opens a composer: the viewer must send it before an agent runs.
The resulting app context is data, not trusted agent instructions. Handoffs
are viewer-bound, expiring and single-use; handle disabled or expired flows.
Testing mini-apps
Use three layers; a successful publish alone is not a runtime test.
- Before publication: test pure logic, input validation and storage behavior. Handlers are ordinary functions: pass a fake request with the fields used, or use
Request,User,AppInfoandStoragefrom the realcodumentor_applibrary when available. In a Codumentor source checkout, its import root issrc/codumentor/plugins/apps/backends/sdk(add it toPYTHONPATHfor local tests). It is injected into published workers, not necessarily installed in the author's shell. Do not vendor it into the app or claim that fake identity/capability tests verify host security. Use a temporary data directory; test two viewer ids and persistence with a new Storage instance. Cover bad/missing input and storage failures. - Frontend preview:
preview_appchecks layout and browser interactions. A workspace preview does not supply the published SDK, identity, storage, consent or backend. Keep any frontend mocks explicit and test-only; do not silently replace failed production requests with demo success. - After approved publication: use the actual URL and a signed-in viewer, standalone and embedded when possible. Check reads/writes, reload persistence, separation between two viewers, shared data only where intended, and useful error states. For capabilities, test allowed, declined and revoked consent; for handoff, confirm the composer and send boundary. Publishing updates the live stable URL; use a separate private test app when testing must not affect existing viewers. Read
app_logsfor failures.
Agents without authenticated browser access or a suitable runtime must state
which checks remain for the user; never bypass authentication or sandboxing.
For Codumentor maintainers, make test-apps-e2e and make test-apps-ui-e2e
exercise the real server/runtime; they require working backend sandboxing
and explicitly skip where it cannot run. These are product-repository tests,
not commands expected in an arbitrary app repository.