Browse Apps
Apps · Build

Functions and UI

Write App functions that read and change the environment's data, call connections, and report errors, and connect the App's UI to them.

9 min read

A function holds one of the App's business rules and runs on BotDojo with the caller's identity and roles. The UI calls functions and table operations with app.call.

Define a function

import { AppError, defineFunction } from "@botdojo/app";

export const approveRequest = defineFunction({
  name: "approve_request",
  description: "Approve or reject a pending request.",
  inputSchema: {
    type: "object",
    properties: { requestId: { type: "string" }, approve: { type: "boolean" } },
    required: ["requestId", "approve"],
    additionalProperties: false,
  },
  outputSchema: { type: "object" },
  tables: { requests: ["read", "patch"] },
  async handler(input, ctx) {
    const row = await ctx.data.get("requests", String(input.requestId));
    if (!row) throw new AppError("NOT_FOUND", "Request not found.");
    if (row.values.status !== "pending") {
      throw new AppError("VALIDATION_FAILED", "Only pending requests can be decided.");
    }
    const limit = Number(ctx.env.APPROVAL_LIMIT);
    if (input.approve && Number(row.values.amount) > limit) {
      throw new AppError("VALIDATION_FAILED", `Amounts over ${limit} need a manager.`);
    }
    const updated = await ctx.data.patch({
      table: "requests",
      rowId: row.id,
      expectedRevision: row.revision,
      values: { status: input.approve ? "approved" : "rejected" },
      requestId: `${ctx.identity.invocationId}:decide`,
    });
    return { id: updated.id, status: updated.values.status };
  },
});
PropertyWhat it does
nameAlso the function's tool name for agents.
inputSchemaValidated before the handler runs.
tablesOptional. The table actions the code may take. The caller's role must permit them too.
connectionsThe connection aliases and tools it calls, from the App's connections.
limitsOverrides of the run limits, such as { wall_ms: 20_000 }.
renamedFromKeeps the function's stable ID through a rename.

Add the function to functions in defineApp, and permit it in the roles that may call it.

The function context

MemberWhat it provides
ctx.identityThe caller's userId, name, email, and roles (for display only), the projectId, and an invocationId.
ctx.envThe backend env vars, with secrets decrypted.
ctx.dataRecords and read-only SQL, within the caller's roles and the function's tables.
ctx.connections.callTool(alias, tool, input)Calls a declared connection tool as the person using the App.

Functions have no network access. Reach other systems through declared connections.

Read and change data

MethodWhat it does
get(table, rowId)One row, or null.
query(table, query?)items and nextCursor. Takes where (eq, lt, lte, gt, gte, in), orderBy, includeArchived, limit, cursor.
create({ table, values, requestId })A new row.
patch({ table, rowId, expectedRevision, values, requestId })Changes only the given fields.
archive({ table, rowId, expectedRevision, requestId })A soft delete.
batch({ operations, requestId })Several writes as one atomic batch.
sql({ sql, params })One read-only SELECT with ? parameters. See Joins and SQL.

Every write takes a requestId. Repeating it returns the first result, so retries are safe: build it from ctx.identity.invocationId plus a step name. sql hides archived rows and caps its results: truncated is true when rows were cut.

Call a connection

export const checkVendor = defineFunction({
  name: "check_vendor",
  // ...description, inputSchema, outputSchema
  connections: { vendors: ["search_vendors"] },
  async handler(input, ctx) {
    return ctx.connections.callTool("vendors", "search_vendors", { name: String(input.vendor_name) });
  },
});

The call runs as the person using the App, through their connection.

Ask for the person's permission

In the UI, ask before you call a function or start a workflow that uses a connection tool:

if (!(await app.permissions.has("vendors", ["search_vendors"]))) {
  await app.permissions.request({
    connections: [{ connection: "vendors", tools: ["search_vendors"] }],
    reason: "To check new vendors against the vendor registry.",
  });
}

Each person sets Allow, Ask each time, or Deny for each tool, and nothing is allowed at first: see What an App may do with a person's connections. app.permissions.check() returns each tool's setting.

Errors

Throw AppError with a code for problems the caller should see. Any other error reaches the caller as FUNCTION_FAILED.

CodeMeaning
VALIDATION_FAILEDValues do not match the schema, or a business rule refused them.
PERMISSION_DENIEDNo role the caller holds permits the operation or table action.
BINDING_DENIEDThe function did not declare the table action or connection tool.
NOT_FOUNDThe row or operation does not exist.
REVISION_CONFLICTThe row changed since it was read.
REQUEST_CONFLICTA requestId was reused with different input.
SQL_REJECTED, SQL_FAILEDThe SQL is not one read-only SELECT, or it failed.
FUNCTION_FAILED, FUNCTION_TIMEOUTThe handler threw an unexpected error or ran too long.
LIMIT_EXCEEDEDThe call went over a run limit.
ENV_INVALIDAn env var is missing or has the wrong type.
CONNECTION_REQUIREDThe person has no connection at the declared path.
PERMISSION_REQUIREDThe person has not allowed the App this connection tool. Its details name the tool.
AUTHORIZATION_REQUIREDThe connection asks for approval first, or an Ask each time tool has nobody to answer.
CONNECTION_FAILEDThe connection call could not run.

Run limits

LimitDefaultMaximum
wall_ms (run time)10 seconds30 seconds
memory_mib256 MiB1024 MiB
output_bytes256 KB1 MB
broker_calls (data and connection calls)2001000

Test the App

botdojo-app test runs test/ against a local copy of the App, with seed.json and the test env vars:

import { test } from "node:test";
import assert from "node:assert/strict";
import { createTestApp } from "@botdojo/app-cli/testing";

test("a requester cannot approve", async () => {
  const app = await createTestApp();
  await assert.rejects(
    app.as("requester").call("approve_request", { requestId: "x", approve: true }),
    { code: "PERMISSION_DENIED" },
  );
  app.close();
});

Connect the UI

The UI is a React app bundled into one HTML file. It runs in an isolated frame with no network access, so bundle or inline every script, font, and image:

import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { connectApp, type AppRow, type BotDojoAppUi } from "@botdojo/app/ui";

function App({ app }: { app: BotDojoAppUi }) {
  const [rows, setRows] = useState<AppRow[]>([]);
  const [error, setError] = useState("");
  const load = () => app.call<{ items: AppRow[] }>("list_requests").then((page) => setRows(page.items));
  const approve = (id: string) =>
    app.call("approve_request", { requestId: id, approve: true }).then(load, (e) => setError(`${e.code}: ${e.message}`));
  useEffect(() => void load(), []);

  return (
    <ul>
      {error && <li>{error}</li>}
      {rows.map((row) => (
        <li key={row.id}>
          {String(row.values.title)}: {String(row.values.status)}{" "}
          {row.values.status === "pending" && app.can("approve_request") && (
            <button onClick={() => approve(row.id)}>Approve</button>
          )}
        </li>
      ))}
    </ul>
  );
}

connectApp().then((app) => createRoot(document.getElementById("root")!).render(<App app={app} />));
MemberWhat it provides
app.contextapp, identity (the person and their role keys), and env (the frontend env vars).
app.onContextChange(listener)Runs when the context changes.
app.call(operation, args)Calls a function or table operation. Throws AppError.
app.can(operation)Whether the caller's roles permit it. A display hint: BotDojo checks every call.
app.openLink(url)Asks the host to open an http or https link.
app.workflowsStarts and follows runs.

Offer tools to the agent

Register tools so the agent can read or act on the App's UI while it is open beside a chat:

await app.registerTools({
  current_view: {
    description: "Read the page, selected request, and status filter in the open App.",
    execute: () => ({ page: currentPage, requestId: selectedId, status: statusFilter }),
  },
});

The tools run in the App's frame, so change records through app.call. registerTools resolves to null where there is no agent, such as Preview App. Claude asks the person before each call, allows at most 64 tools, and waits at most 45 seconds for an answer.

The App's frame cannot change the browser's address, so report each page with setRoute: BotDojo keeps it in the URL as ?app_route=…, and a reload or a shared link reopens it.

import { matchAppRoute } from "@botdojo/app/ui";

const ROUTES = [{ path: "/requests" }, { path: "/requests/:requestId" }];

function pageFor(route: string | null) {
  const match = matchAppRoute(route, ROUTES);
  if (match?.path === "/requests/:requestId") return { page: "request", id: match.params.requestId };
  if (match?.path === "/requests") return { page: "list" };
  return { page: "home" }; // The home page, and any route the App doesn't have.
}

let view = pageFor(app.initialRoute);
app.onNavigate((route) => show((view = pageFor(route))));

// When the user opens a request:
app.setRoute(`/requests/${encodeURIComponent(id)}`, { title: requestNumber });

Treat routes as untrusted input: look up the record through app.call, and show a "not found" page when that fails. Without an onNavigate listener, BotDojo reloads the App at the new route.

Declare pages for agents

List the App's pages in ui.routes so agents can open them with show_app:

ui: {
  entry: "ui/main.tsx",
  routes: [
    { path: "/requests", description: "All requests" },
    { path: "/requests/:requestId", description: "One request, by ID" },
  ],
},

BotDojo refuses an agent's route that matches none of them. Without ui.routes, agents can pass any route.

Offer a chat beside the App

Set ui.chat: true to show a Chat button where the App opens on its own page: the Apps page, its shared link, and its window. It opens the person's Workspace agent beside the App, with the tools the App registers.

Send a message and share page state

Call app.sendMessage from a button such as Ask about this request. On the App's own page, this needs ui.chat.

await app.sendMessage(`Help me review request ${requestNumber}.`);

Call app.setModelContext when the selection changes. Each call replaces the last, and null clears it:

await app.setModelContext({
  text: `Viewing request ${requestNumber}`,
  data: { page: "request", requestId: id },
});

It resolves to false on hosts that ignore it, including BotDojo's own pages. There, register a tool such as current_view.

Fit the host: theme and fullscreen

app.applyHostStyles(); // The host's colors and fonts as CSS variables, and light or dark mode.

// On a button click: hosts require one before going fullscreen.
await app.requestDisplayMode("fullscreen"); // Or "pip". Resolves to the mode the host uses.
  • Declare each mode besides inline in ui.displayModes, such as ["fullscreen"]. A host never switches to an undeclared mode.
  • app.host has the host's theme, styles, displayMode, locale, timeZone, and platform. app.onHostChange(listener) runs when they change.
  • Use the CSS variables with a fallback, such as var(--color-background-primary, #fff).
  • In a Workspace chat, fullscreen opens the App as a tab. On the App's own page it fills the page until Esc. Claude uses its own fullscreen.

Show loading while the data store starts

A SQLite Store can take time to wake, so poll app.store.status() after connectApp() before you load records:

const app = await connectApp();
showLoading("Getting your data ready…");

try {
  const deadline = Date.now() + 120_000;
  for (;;) {
    const status = await app.store.status();
    if (status.ready) break;
    if (status.state === "error") throw new Error(status.message ?? "Unable to start the data store.");
    if (Date.now() >= deadline) throw new Error("The data store is taking longer than expected. Try reopening the app.");
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
  await loadRecords(app);
} catch (error) {
  showError(error instanceof Error ? error.message : "Unable to load your data.");
} finally {
  hideLoading();
}

state is ready, sleeping, starting, stopping, or error. DataSets and local Stores are ready at once. Do not name an operation of your own store_status.

Next steps