A form that writes back

A page with a Form whose submissions the dev server checks and stores, then serves back as a read-only table. The server owns the form: its fields, their rules and where submissions go. The browser sends a form id and values, never SQL, a table or a path.

How it works:

  • forms in the server config defines each form. The server checks every value against its field and stores nothing if any value is wrong. Each error comes back with the field it belongs to.
  • Submissions are appended to <storeDir>/forms/<form id>.jsonl, one line each, with the server's submission id and the time.
  • A DuckDB source reads that file as a table. Its queries go through the same read-only checks as any other source, so the data can be filtered, charted and exported, but not changed.

The server config:

config.ts:

ts
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { type SurfacesConfig, defineConfig } from "@surfaces-ui/dev-server";

const here = path.dirname(fileURLToPath(import.meta.url));

/**
 * A store visit form the server owns: its fields, their rules and where
 * submissions are kept are all set here. A client sends a form id and
 * values, nothing else.
 *
 * The server appends each submission to `<storeDir>/forms/store-visit.jsonl`.
 * The `forms` source reads that same file as a read-only table, so what was
 * submitted can be queried, charted and exported like any other data.
 */
export function writebackConfig(storeDir = path.join(here, ".surfaces")): SurfacesConfig {
  const submissions = path.join(storeDir, "forms", "store-visit.jsonl");
  // The table is a view over the file, so the file must exist when the server starts; empty is fine.
  fs.mkdirSync(path.dirname(submissions), { recursive: true });
  fs.closeSync(fs.openSync(submissions, "a"));

  return defineConfig({
    forms: [
      {
        id: "store-visit",
        title: "Store visit",
        description: "What you found on a visit to a store.",
        // Shown to people so they know where the data goes. The server, not this text, decides.
        target: "forms.store_visits",
        fields: [
          { name: "store", label: "Store", type: "choice", options: ["Leeds", "York", "Hull"], required: true },
          { name: "visited_on", label: "Visited on", type: "date", required: true },
          { name: "rating", label: "Rating", type: "integer", min: 1, max: 5, required: true, help: "1 is poor, 5 is excellent." },
          { name: "follow_up", label: "Needs a follow-up visit", type: "boolean" },
          { name: "note", label: "Note", type: "longtext", maxLength: 500 },
        ],
      },
    ],
    sources: [{ id: "forms", displayName: "Form submissions", engine: "duckdb", tables: [{ name: "store_visits", format: "json", path: submissions, comment: "One row per store visit form submitted." }] }],
    discovery: { storeDir },
    // A submission does not clear kept results, so a kept query over this file would miss
    // later submissions. Every query here is read from the file as it is now.
    storedResults: false,
  });
}

surfaces-dev loads it from surfaces.config.ts:

surfaces.config.ts:

ts
import { writebackConfig } from "./config.js";

/** What `surfaces-dev` loads: submissions and the read-only table over them live in .surfaces next to this file. */
export default writebackConfig();

The page is a PageDocument. Its Form names the server's form by id and repeats the fields, so the browser can point out mistakes before anything is sent. The server checks them again either way:

page.ts:

ts
import { type PageDocument, analyticsCatalog } from "@surfaces-ui/spec";

/**
 * The page a person fills in. The Form names the server's form by id and
 * repeats its fields so it can check them before sending; the server checks
 * them again and decides where they are stored. Nothing here names a table
 * or holds SQL that writes.
 */
export const storeVisitPage: PageDocument = {
  id: "store-visit",
  title: "Log a store visit",
  catalogId: analyticsCatalog.id,
  components: [
    { id: "root", component: "Column", children: ["heading", "intro", "form"] },
    { id: "heading", component: "Text", variant: "h2", text: "Log a store visit" },
    { id: "intro", component: "Text", variant: "body", text: "Saved to the forms source, where the team's visit report reads it." },
    {
      id: "form",
      component: "Form",
      formId: "store-visit",
      title: "Store visit",
      fields: [
        { name: "store", label: "Store", type: "choice", options: ["Leeds", "York", "Hull"], required: true },
        { name: "visited_on", label: "Visited on", type: "date", required: true },
        { name: "rating", label: "Rating", type: "integer", min: 1, max: 5, required: true, help: "1 is poor, 5 is excellent." },
        { name: "follow_up", label: "Needs a follow-up visit", type: "boolean" },
        { name: "note", label: "Note", type: "longtext", maxLength: 500 },
      ],
      submitLabel: "Save visit",
      // Tells the agent (or the host) what was stored, with the server's submission id.
      action: { event: { name: "visit_logged" } },
    },
  ],
};

In the browser, FormsProvider gives every Form beneath it somewhere to send. connectForms reaches the dev server's FormService:

StoreVisit.tsx:

tsx
import { connectForms } from "@surfaces-ui/client-connect";
import { FormsProvider } from "@surfaces-ui/components";
import { type SurfaceAction, analyticsCatalog, pageSurface } from "@surfaces-ui/spec";
import { SurfaceView, analyticsRenderers } from "@surfaces-ui/spec/react";
import { useMemo } from "react";
import { storeVisitPage } from "./page.js";

export interface StoreVisitProps {
  /** Where the dev server is, e.g. http://localhost:5220; or a transport of your own. */
  server: Parameters<typeof connectForms>[0];
  /** Called after the server stored a visit, with its values as stored and the submission id. */
  onAction?(action: SurfaceAction): void;
}

/** In the browser: the page, with its Form sending to the server's FormService. */
export function StoreVisit({ server, onAction }: StoreVisitProps) {
  const forms = useMemo(() => connectForms(server), [server]);
  const surface = useMemo(() => pageSurface(storeVisitPage), []);
  return (
    <FormsProvider forms={forms}>
      <SurfaceView surface={surface} catalog={analyticsCatalog} renderers={analyticsRenderers} onAction={(action) => onAction?.(action)} />
    </FormsProvider>
  );
}
tsx
<StoreVisit server={{ baseUrl: "http://localhost:5220" }} onAction={sendToAgent} />

After the server stores a visit, the visit_logged event carries the values as stored and the server's submission id. Before that, nothing was saved. To read the visits back, query the forms source. Each row holds id, formId, submittedAt and the submitted values:

sql
SELECT values.store AS store, CAST(values.visited_on AS DATE) AS visited_on, values.rating AS rating
FROM store_visits
ORDER BY submittedAt DESC

The tests start the dev server in-process on a free port, with a temporary store folder. The first test submits over Connect, then reads the rows back through connectDataSource. It also checks that bad values, unknown forms and SQL hidden in the values are all refused:

writeback.test.ts:

ts
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createConnectTransport } from "@connectrpc/connect-node";
import { connectDataSource, connectForms } from "@surfaces-ui/client-connect";
import { type DataSource, type Forms, collect, formDefinitions, toRows } from "@surfaces-ui/data";
import { type SurfacesServer, createSurfacesServer, openSources, serverOptions } from "@surfaces-ui/dev-server";
import { create } from "@bufbuild/protobuf";
import { type FormFieldSpec, formDefinition } from "@surfaces-ui/components";
import { type FormDefinition, FormDefinitionSchema, SubmitRequestSchema } from "@surfaces-ui/proto";
import { analyticsCatalog, pageMessages, validatePage } from "@surfaces-ui/spec";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { writebackConfig } from "./config.js";
import { storeVisitPage } from "./page.js";

let store: string;
let server: SurfacesServer;
let url: string;
let forms: Forms;
let data: DataSource;

const plain = (value: unknown) => JSON.parse(JSON.stringify(value, (_k, v) => (typeof v === "bigint" ? Number(v) : v)));
const lines = () => fs.readFileSync(path.join(store, "forms", "store-visit.jsonl"), "utf8").split("\n").filter(Boolean);

beforeAll(async () => {
  store = fs.mkdtempSync(path.join(os.tmpdir(), "surfaces-writeback-"));
  const config = writebackConfig(store);
  server = await createSurfacesServer(await serverOptions(config, await openSources(config, store), store));
  ({ url } = await server.listen(0));
  const transport = createConnectTransport({ baseUrl: url, httpVersion: "1.1" });
  forms = connectForms({ transport });
  data = connectDataSource({ transport });
}, 60_000);

afterAll(async () => {
  await server?.close();
  if (store) fs.rmSync(store, { recursive: true, force: true });
});

describe("the page", () => {
  it("is valid against the catalog, as a page and as A2UI messages", () => {
    expect(validatePage(storeVisitPage, analyticsCatalog)).toEqual([]);
    for (const message of pageMessages(storeVisitPage)) expect(analyticsCatalog.validateMessage(message)).toEqual([]);
  });

  it("checks the same rules the server will", () => {
    const form = storeVisitPage.components.find((c) => c.component === "Form")!;
    const [server] = formDefinitions(writebackConfig(store).forms!);
    // Help text may differ between the two; the rules may not.
    const rules = (definition: FormDefinition) => definition.fields.map(({ name, label, type, required, options, min, max, maxLength, pattern }) => ({ name, label, type, required, options, min, max, maxLength, pattern }));
    expect(form.formId).toBe(server!.id);
    expect(rules(formDefinition(String(form.formId), form.fields as FormFieldSpec[]))).toEqual(rules(create(FormDefinitionSchema, server)));
  });
});

describe("submitting", () => {
  it("stores a good submission, and the forms source reads it back", async () => {
    const response = await forms.submit({
      formId: "store-visit",
      values: { store: "York", visited_on: "2026-11-12", rating: "4", note: "Shelves restocked." },
      idempotencyKey: "visit-1",
    });
    expect(response.fieldErrors).toEqual([]);
    // As stored: the rating is a number now, and fields left blank are null.
    expect(response.submission?.values).toEqual({ store: "York", visited_on: "2026-11-12", rating: 4, follow_up: null, note: "Shelves restocked." });

    // The same key again stores nothing new.
    const again = await forms.submit({ formId: "store-visit", values: { store: "York", visited_on: "2026-11-12", rating: 4 }, idempotencyKey: "visit-1" });
    expect(again.submission?.id).toBe(response.submission?.id);
    expect(lines()).toHaveLength(1);

    const { submissions } = await forms.listSubmissions({ formId: "store-visit" });
    expect(submissions.map((s) => s.id)).toEqual([response.submission!.id]);

    // Read back through the read-only DataSource, filtered and sorted in SQL like any table.
    const result = await collect(
      data.execute({
        sourceId: "forms",
        query: { baseSql: "SELECT id, values.store AS store, CAST(values.visited_on AS DATE) AS visited_on, values.rating AS rating FROM store_visits ORDER BY submittedAt DESC" },
      }),
    );
    expect(plain(toRows(result.table))).toEqual([{ id: response.submission!.id, store: "York", visited_on: Date.UTC(2026, 10, 12), rating: 4 }]);
  });

  it("refuses bad values with a reason per field, and stores nothing", async () => {
    const bad = await forms.submit({ formId: "store-visit", values: { store: "Paris", visited_on: "2026-02-30", rating: 9 } });
    expect(bad.submission).toBeUndefined();
    expect(Object.fromEntries(bad.fieldErrors.map((e) => [e.field, e.message]))).toEqual({
      store: "Choose one of: Leeds, York, Hull.",
      visited_on: "That date does not exist.",
      rating: "Must be at most 5.",
    });
    const missing = await forms.submit({ formId: "store-visit", values: {} });
    expect(missing.fieldErrors.map((e) => e.field).sort()).toEqual(["rating", "store", "visited_on"]);
    expect(lines()).toHaveLength(1);
  });

  it("refuses a form the server does not define", async () => {
    for (const formId of ["no-such-form", "../../etc/passwd", "store_visits"]) {
      const response = await forms.submit({ formId, values: { store: "York" } });
      expect(response.submission).toBeUndefined();
      expect(response.message).toMatch(/^No form/);
    }
    expect(fs.readdirSync(path.join(store, "forms"))).toEqual(["store-visit.jsonl"]);
  });
});

describe("what a client can send", () => {
  it("has no field for SQL, a table or a path", () => {
    expect(SubmitRequestSchema.fields.map((f) => f.name)).toEqual(["form_id", "values", "surface_id", "idempotency_key"]);
    // A form's definition says where data goes only as text for people to read.
    expect(FormDefinitionSchema.fields.map((f) => f.name)).toEqual(["id", "title", "description", "fields", "target"]);
  });

  it("treats SQL or a table in the values as unknown fields", async () => {
    const response = await forms.submit({
      formId: "store-visit",
      values: { store: "York", visited_on: "2026-11-12", rating: 3, table: "orders", sql: "DELETE FROM store_visits" },
    });
    expect(response.submission).toBeUndefined();
    expect(response.fieldErrors.map((e) => [e.field, e.message])).toEqual([
      ["table", "This form has no such field."],
      ["sql", "This form has no such field."],
    ]);
    expect(lines()).toHaveLength(1);
  });

  it("drops fields the contract does not have from a hand-made request", async () => {
    const response = await fetch(`${url}/surfaces.v1.FormService/Submit`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ formId: "store-visit", values: { store: "York", visited_on: "2026-11-12", rating: 3 }, table: "orders", sql: "DROP TABLE orders" }),
    });
    // The server reads only the fields SubmitRequest declares; the rest never reach the form.
    expect(response.ok).toBe(true);
    const { submission } = (await response.json()) as { submission: { values: Record<string, unknown> } };
    expect(submission.values).toEqual({ store: "York", visited_on: "2026-11-12", rating: 3, follow_up: null, note: null });
    expect(lines()).toHaveLength(2);
    expect(lines()[1]).not.toMatch(/orders|DROP/);
  });

  it("cannot write through the forms source", async () => {
    await expect(collect(data.execute({ sourceId: "forms", query: { baseSql: "DELETE FROM store_visits" } }))).rejects.toThrow();
    await expect(collect(data.execute({ sourceId: "forms", query: { baseSql: "COPY store_visits TO 'elsewhere.csv'" } }))).rejects.toThrow();
  });
});

The second draws the page in jsdom against the same server. It fills the form in and checks the event:

store-visit.test.tsx:

tsx
// @vitest-environment jsdom
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createConnectTransport } from "@connectrpc/connect-node";
import { type SurfacesServer, createSurfacesServer, openSources, serverOptions } from "@surfaces-ui/dev-server";
import type { SurfaceAction } from "@surfaces-ui/spec";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { writebackConfig } from "./config.js";
import { StoreVisit } from "./StoreVisit.js";

let store: string;
let server: SurfacesServer;
let transport: ReturnType<typeof createConnectTransport>;

beforeAll(async () => {
  store = fs.mkdtempSync(path.join(os.tmpdir(), "surfaces-store-visit-"));
  const config = writebackConfig(store);
  server = await createSurfacesServer(await serverOptions(config, await openSources(config, store), store));
  const { url } = await server.listen(0);
  transport = createConnectTransport({ baseUrl: url, httpVersion: "1.1" });
}, 60_000);
afterAll(async () => {
  await server?.close();
  if (store) fs.rmSync(store, { recursive: true, force: true });
});
afterEach(cleanup);

describe("the store visit page in a browser", () => {
  it("checks the fields, sends only the form id and values, and reports the stored submission", async () => {
    const onAction = vi.fn<(action: SurfaceAction) => void>();
    render(<StoreVisit server={{ transport }} onAction={onAction} />);

    // Wrong values are caught before anything is sent.
    fireEvent.change(screen.getByLabelText(/^Rating/), { target: { value: "7" } });
    await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save visit" })));
    expect(screen.getByText("Must be at most 5.")).toBeTruthy();
    expect(screen.getByText("Store is required.")).toBeTruthy();
    expect(onAction).not.toHaveBeenCalled();
    expect(fs.readFileSync(path.join(store, "forms", "store-visit.jsonl"), "utf8")).toBe("");

    fireEvent.click(screen.getByLabelText("Hull"));
    fireEvent.change(screen.getByLabelText(/^Visited on/), { target: { value: "2026-11-10" } });
    fireEvent.change(screen.getByLabelText(/^Rating/), { target: { value: "2" } });
    fireEvent.click(screen.getByLabelText("Needs a follow-up visit"));
    await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save visit" })));

    expect(await screen.findByText("Saved.")).toBeTruthy();
    const action = onAction.mock.calls[0]![0];
    expect(action).toMatchObject({ name: "visit_logged", context: { formId: "store-visit", values: { store: "Hull", visited_on: "2026-11-10", rating: 2, follow_up: true, note: null } } });
    const { submissions } = await server.forms!.listSubmissions({ formId: "store-visit" });
    expect(action.context.submissionId).toBe(submissions[0]!.id);
  });
});

Things to know:

  • The table is a view over the file, so the file must exist when the server starts. The config creates it empty. Its columns are worked out from what has been submitted, so a query that names a field fails until a submission has a value for it.
  • A submission does not clear kept results, so a kept query over this table would miss later submissions. The config sets storedResults: false. With other sources on the same server, turn kept results off only where you need to, or pass a fresh notBefore when reading.
  • The page repeats the server's fields. Keep the two the same: the test compares them. A required field that is missing from the page cannot be filled in, and the server refuses every submission.
  • A hand-made request with fields that SubmitRequest does not have, such as table or sql, is not rejected. Those fields are dropped, and only the declared ones reach the form.
  • Submissions are kept in a file on the server's disk. This has not been run with more than one server process writing to the same folder, and no form has written to a database table.

Source and test: apps/recipes/src/form-writeback