Tutorial 2: your code, and breaking things on purpose
On this page
Goal: finish unafraid of regeneration. You will write a binding and a backend rule, give the rule a test, then break the project three ways and read what the tool says each time.
You need the project from Tutorial 1, with npx globetrotter dev running and the app open at /g/things. Every step here was run on that project. The commands use the default ports (app 3000, backend 8000); use yours if you chose others.
1. Who owns which file
| Path | Owner | What sync does to it |
|---|---|---|
designs/*.design.json, designs/*.service.json |
you, the studio, an agent | never touches them; they are the source |
frontend/src/generated/* |
generated | rewrites on every change; a hand edit is saved to .hand-edited/ first |
frontend/src/bindings/<page>.ts |
yours once you edit it | before your first edit it is a stub that follows the design; after, never again |
backend/packages/<app>_contract, _core, _fastapi |
generated | rewrites |
backend/packages/<app>_impl/* |
yours once you edit it | same as bindings: a stub that follows the design until you edit it |
backend/tests/* |
stubs the tool wrote, then yours | stubs follow the design; a test you wrote or edited is never deleted |
backend/migrations/ |
written once per change | adds new files, never changes one |
vendor/, package.json, globetrotter.config.json, .env |
yours | not touched (except by install.mjs upgrade) |
How to tell, any time: the first lines of a file say. A stub says @stub-hash … edit anything and it is yours; generated code says @generated-hash. Open frontend/src/bindings/my-first-app--things.ts now: its first line is the stub-hash line. You are about to edit it, and that line is how sync will know it is yours.
2. A binding: a notice (5 minutes)
The generated page already knows how to show a notice (a snackbar) if the binding returns one. Make pressing the check button say what happened.
In frontend/src/bindings/my-first-app--things.ts make three edits.
After const [said, setSaid] = useState(false); add:
// What the last press did, in words: the app shows it as its snackbar.
const [notice, setNotice] = useState<string>();Replace the pack: line, which is:
pack: (item) => { void call("/things/actions/pack", { id: (item as Record<string, unknown>).id }); },with:
pack: (item) => { void call("/things/actions/pack", { id: (item as Record<string, unknown>).id }).then((res) => { if (res) setNotice(`${item.title} is packed.`); }); },call is the helper the stub wrote: it sends the request to /api/…, folds the answer into data, and gives back the answer, or null if the backend refused. So res is truthy only when it worked.
In the returned object, change status, error, said, fieldErrors, to status, error, said, fieldErrors, notice,.
Then:
npx globetrotter sync
(cd frontend && npx tsc --noEmit && echo TSC-OK)sync says nothing about your file: it is yours now, and git status shows it modified. Add a thing, press its check: the snackbar at the bottom says "Snacks is packed." (type your own thing's name).
3. A binding: a value you derive (10 minutes)
A page can show a value no table holds: "2 of 5 packed". The design says the page needs summary; the binding provides it.
Find the id of the Stack that holds the "Packing tip" button (get_page outline, last Stack in the content), and add a text bound to a path the data does not have yet:
add_node({ design: "my-first-app", page: "Things", target: { kind: "slot", parentId: "<that Stack's id>", slot: "children" },
type: "Text", props: { text: { "$bind": "summary", "sample": "2 of 5 packed" }, variant: "titleMedium" } })In the studio: select the Stack, Add, a Text, and bind its text to summary ("Where do its words come from?" in the panel).
Now the page's generated types say data.summary: string is required, and your binding, which no longer follows the design, does not provide it. Run:
npx globetrotter sync
echo $?sync writes the page and exits 0 (it did its job); the broken file is yours, so it does not touch it. The checks tell you:
npx globetrotter sync --check✗ tsc --noEmit in frontend/: 1 error, the bindings do not fit the generated types (a binding is yours: edit it to the new types, or `--no-tsc` to skip)
frontend/src/bindings/my-first-app--things.ts:41 TS2345: Argument of type '{ draft: { title: string; who: string; }; noMatch: never[]; query: string; things: never[]; }' is not assignable to parameter of type 'ThingsData | (() => ThingsData)'.and (cd frontend && npx tsc --noEmit) ends: "Property 'summary' is missing in type … but required in type 'ThingsData'." (doctor shows the same as ✗ generated types = bindings.) This is the design working: a promise the page made and your code has not kept yet. Keep it.
In the binding add summary: '', to the initial useState<ThingsData>({ … }) object, after query: '',; and in the returned data: add a computed one before noMatch:
data: { ...data, summary: data.things.length ? `${data.things.filter((t) => t.packed).length} of ${data.things.length} packed` : '', noMatch: …(cd frontend && npx tsc --noEmit && echo TSC-OK) passes. In the app, "1 of 3 packed" sits under the Packing tip button and changes as you press the checks. Commit: git add -A && git commit -m "notice and summary".
4. A backend rule, with a test (15 minutes)
The design can say "a title is 1 to 80 characters". It cannot say "no thing twice". That is code. The stub for the service is backend/packages/my_first_app_impl/src/my_first_app_impl/things.py; its class ThingsImpl subclasses the generated ThingsBase. Override one method and call the generated one for the rest.
Replace the whole file with the version you would write first:
"""The Things service: your code. Override any operation of ThingsBase."""
from my_first_app_contract import models as m
from my_first_app_core.errors import InvalidInput
from my_first_app_core.services import ThingsBase
class ThingsImpl(ThingsBase):
async def create(self, ctx, *, title: str, who: str | None = None) -> m.ThingsData:
"""The generated create, after one rule the design cannot say: no thing twice."""
wanted = title.strip().lower()
for row in await ctx.db.thing.find(unbounded=True):
if row.title.strip().lower() == wanted:
raise InvalidInput({"title": f"{row.title} is already on the list."})
return await super().create(ctx, title=title, who=who)ctx.db.thing is the repository for the thing entity (get, find, create, update). InvalidInput({"title": "…"}) is a 400 that names the field, so the page can put the sentence under it. dev watches backend/ and reloads; one second later:
curl -s -XPOST localhost:8000/things/actions/create -H 'content-type: application/json' -d '{"title":"Snacks"}'
curl -s -XPOST localhost:8000/things/actions/create -H 'content-type: application/json' -d '{"title":"snacks"}'{"error":"Snacks is already on the list.","field":"title","fields":{"title":"Snacks is already on the list."}}Write the test. backend/tests/test_things_twice.py:
"""No thing is put on the list twice (ThingsImpl.create)."""
def test_a_thing_twice_is_refused(client):
first = client.post("/things/actions/create", json={"title": "Card table"})
assert first.status_code == 200
again = client.post("/things/actions/create", json={"title": " card TABLE "})
assert again.status_code == 400
assert again.json()["fields"] == {"title": "Card table is already on the list."}client is a fixture the tool's conftest.py provides: the real app, in process, on a fresh throwaway database for each test (your own database is never touched).
cd backend && uv run pytest -qFAILED tests/test_contract.py::test_contract[POST /things/actions/create] - +...
1 failed, 14 passed in 3.14sYour test passes. A test you did not write fails. Read it:
uv run pytest -q tests/test_contract.py | - ST202 Schema-valid request rejected
| Valid data should have been accepted
| Expected: 2xx, 3xx, 401, 403, 404, 409, 429, 5xx
| [400] Bad Request:
| `{"error":"0 is already on the list.","field":"title","fields":{"title":"0 is already on the list."}}`
| Reproduce with:
| curl -X POST -H 'Content-Type: application/json' -d '{"title": " 0 …", "who": ""}' http://testserver/things/actions/createWhat happened: test_contract.py is written by the tool from the contract. It calls every operation with every input the contract allows (here, a title the schema accepts), and checks that each answer is one the contract lists. A title of "0" was added once, then added again, so your rule said 400. But the contract promises that a title that fits its rules is accepted, and lists 409 as the status for "not now". Your code lied to the contract; the test caught it.
The fix is to tell the design that this operation may refuse this way. A refusal declared in the design is listed in the contract and generated as a class.
add_service_node({ design: "my-first-app", type: "Refusal", target: { parent: "items-create", slot: "refuses" },
props: { name: "alreadyOnList", status: "409", message: "That is already on the list." } })(Studio: Backend → Services, click POSTcreate, + Refusal.) dev regenerates backend/packages/my_first_app_core/src/my_first_app_core/errors.py, which now has:
class AlreadyOnList(Refused):
"""That is already on the list. (409)"""
status = 409
message = "That is already on the list."Use it. In things.py import AlreadyOnList instead of InvalidInput, and write raise AlreadyOnList(). In the test, expect 409 and again.json()["error"] == "That is already on the list.".
cd backend && uv run pytest -q............... [100%]
15 passed in 2.19sIn the app, adding card table twice now shows "That is already on the list." in the snackbar. A declared refusal has words, a status and no field: the page cannot put it under an input. When the sentence must sit under a field, put the rule in the design (the field's length, pattern or format, as you did for the title in Tutorial 1): then the contract itself says what is valid, and the test and the page agree for free. Use InvalidInput only for a value the contract also refuses.
Format check: the tool also holds your Python to ruff format. If a line you wrote is too long, doctor says so and names the file and line; the fix is cd backend && uv run ruff format ..
5. Break it on purpose
Commit first: git add -A && git commit -m "before breaking things". Breaks 5.1 and 5.3 can be undone with git checkout -- . and npx globetrotter sync; 5.2 also writes a migration, so you fix it forward, as shown.
5.1 Edit a generated file
sed -i '' 's/>Packing tip</>Packing hint</' frontend/src/generated/my-first-app--things.tsx(On Linux: sed -i 's/…/…/'.) Now ask the tool:
npx globetrotter sync --check! frontend/src/generated/my-first-app--things.tsx (out of date, and edited by hand: a sync keeps the edit in .hand-edited/ and writes the file again)
…
generated files were out of date--check changed nothing (it exits 1). Run the real thing:
npx globetrotter sync→ frontend/src/generated/.hand-edited/my-first-app--things.2026-12-03T21-32-11-091Z.tsx (your edits, preserved)
→ frontend/src/generated/my-first-app--things.tsxYour edit is in the .hand-edited copy; the real file says "Packing tip" again. Nothing was lost, and nothing you do in a generated file survives. (.hand-edited/ is in .gitignore: it is a safety copy on your machine, not part of the project.) Delete it: rm -rf frontend/src/generated/.hand-edited. What you wanted was in the design: the word is Button "Packing tip"; change it there (set_props, or select it in the studio).
5.2 Rename a field in the design
set_service_props({ design: "my-first-app", node: "who", props: { name: "bringer" } })The answer is long and worth reading. It says what followed by itself (the create's param, the page's draft.who), what it could not carry (words in a description), and:
"handEditedBindings": [
"frontend/src/bindings/my-first-app--things.ts line 24, 44, 74, 93: change who → bringer"
]
…
"next": "run sync …: 0004_rename_thing_who.sql is not written yet, so the database does not know this change; sync writes it, never applies"Run the sync and read the lines starting with !:
npx globetrotter sync→ backend/migrations/db/sqlite/0004_rename_thing_who.sql
! my_first_app_impl/things.py (ThingsImpl.create): the design gave it bringer, which its code does not take: add bringer: str | None = None to its signature after the * (the route passes it; until then the call fails)
! my_first_app_impl/things.py (line 15): your code names who, which the design renamed to bringer on thing (migration 0004; the values stay): it fails with AttributeError or KeyError until it says bringerThe tool read your Python and named both places. (Your migration number may differ: it is the next free one.) Check what else is broken:
npx globetrotter doctor✗ generated types = bindings: 2 type errors: frontend/src/bindings/my-first-app--things.ts:44 TS2353, frontend/src/bindings/my-first-app--things.ts:93 TS2339
✗ migrations written = applied (local): The backend is behind its migrations: 0004 is waiting …and the app: curl -s -XPOST localhost:3000/api/things/actions/create -H 'content-type: application/json' -d '{"title":"Plates","bringer":"Jo"}' answers
{"error":"Something went wrong on the server; it is in the server’s log.","detail":"TypeError: ThingsImpl.create() got an unexpected keyword argument 'bringer'","at":"my_first_app_fastapi/routers/things.py:33, in things_create"}four tests fail in uv run pytest -q. Everything is named. Fix it:
perl -pi -e 's/\bwho\b/bringer/g' frontend/src/bindings/my-first-app--things.ts backend/packages/my_first_app_impl/src/my_first_app_impl/things.py
cd backend && GLOBETROTTER_ENV=local uv run python -m my_first_app_core.migrate && uv run ruff format . && uv run pytest -q && cd ..
(cd frontend && npx tsc --noEmit && echo TSC-OK)
npx globetrotter doctor(perl, not sed, because macOS's sed has no \b.) The migration renames the column and keeps the rows. doctor ends: everything that can be checked is in sync. If your own test used "who", it fails too and tells you: that is what tests are for.
5.3 Delete a design node that a binding still reads
find_nodes({ design: "my-first-app", query: "summary" }) // the id of the summary text
remove_node({ design: "my-first-app", page: "Things", nodeId: "<that id>" })
npx globetrotter sync --check✗ tsc --noEmit in frontend/: 2 errors, the bindings do not fit the generated types …
frontend/src/bindings/my-first-app--things.ts:48 TS2353: Object literal may only specify known properties, and 'summary' does not exist in type 'ThingsData | (() => ThingsData)'.
frontend/src/bindings/my-first-app--things.ts:91 TS2353: …The reverse of 5.2: the page no longer needs summary, and your binding still gives it. You have two ways out. Put the node back: git checkout -- designs frontend/src/generated, then npx globetrotter sync (in the studio: Undo, top bar). Or delete the two summary lines from the binding. Either way doctor is green again.
6. What you can now rely on
- A generated file is never the place for your work, and the tool never hides that it rewrote one.
- A file you edited in
bindings/or_impl/is never rewritten. When the design changes under it, you get a type error (frontend) or a!line naming the file and line (backend), never silence. - The database changes only when you run
migrate. The files that change it are written once and are plain SQL you can read first. - Your tests run against a throwaway database. The tool's contract test is the judge of whether your rule agrees with the design.
- Anything that goes wrong has a command that says so:
sync --check,doctor,tsc,pytest.
Next: a tour of Rally.