← Palstart
Raw markdown

Building apps for Palstart

This page is written for AI assistants (ChatGPT, Claude, Gemini, Copilot and others) and for people who help a Palstart student write code. It describes exactly what a Palstart app is, what it can use, what it cannot, and the one format in which code has to come back so the student can paste it into Palstart and have it run first time.

Raw text of this page for machines: https://palstart.app/llms.txt (also https://palstart.app/docs.md). Always read the current version; the platform changes.

If you only read one section, read The delivery contract. Code that follows it goes in with one paste. Code that does not is retyped by the student or thrown away.

The format in ten lines

  • Plain JavaScript and React 18 with JSX. No TypeScript, ever.
  • Every file is complete, in its own fenced block, with // filename: src/... as the first line inside the fence.
  • src/App.jsx is the entry and ends with export default App. Other files live under src/ and are imported with relative paths.
  • The only package you may import is react. No npm. No package.json, index.html, main.jsx, config files or server files.
  • Tailwind classes, <iconify-icon> icons, /api/build-image pictures. No emoji, no other image hosts.
  • Saving, accounts, multiplayer and live data: appPlayer, appData, appAuth, appRoom, callService. AI: POST /api/build-ai. All are globals in the page; never localStorage, never your own server, never a fetch to another site.
  • No ?., no ??, no async/await, no arrow-function components, no arrow .map callbacks, no components inside components.
  • No links to other websites, no messaging between people, no real guns and nothing killed in games, no API keys in code.
  • Mobile apps: an h-dvh flex column with text-base inputs. Web apps: full width with a header or sidebar.
  • One short sentence to the student, then the code. If you give files to download instead, use the same paths in a folder or a zip.

What Palstart is

Palstart is a school platform where students aged 8 to 18 build real web apps and games by talking to an AI builder called Pal. A project is a small React code base under src/ that runs in a sandboxed browser frame, with a hosted backend Palstart provides. Students can deploy their app to a public link, put it in a class Showcase, and remix each other's work.

Students are allowed to take their code to another AI and bring the answer back through the Paste code sheet in BuildLab. That is the moment this page is for. The paste is read by a parser, checked by an audit, and run as it is. No model cleans it up.


The delivery contract

Give the student back whole files, with their paths. Every file you changed or created, complete from the first line to the last. Never "the rest stays the same", never a diff, never a snippet with ... in it.

Each file is one fenced code block. The parser accepts either of these two forms. The first is preferred.

Form A, a filename comment as the very first line inside the fence:

jsx
// filename: src/App.jsx
import React, { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  return <button onClick={function () { setCount(count + 1); }}>{count}</button>;
}

export default App;

Form B, a heading with the path on the line above the fence:

src/game/player.js

js
export function makePlayer() {
  return { x: 100, y: 200, vy: 0 };
}

Rules for the whole answer:

  • Plain JavaScript and React 18 with JSX. No TypeScript, no .ts or .tsx, no type annotations, no interface.
  • src/App.jsx is the entry and must end with export default App. A single-file project is just src/App.jsx.
  • Every file lives under src/ and ends in .js, .jsx or .css. Folders are fine: src/components/Card.jsx, src/game/level.js. Paths match ^src/([A-Za-z0-9_-]+/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*\.(js|jsx|css)$.
  • No other files. No package.json, no index.html, no main.jsx, no vite.config, no .env, no server, no README. They are ignored or refused.
  • Nothing to install. The only package you may import is react (and react-dom, which is the same global). Everything else listed under "What is loaded in the page" is a global, used without an import.
  • Keep each file under about 400 lines. The builder's own limit is 600 lines in one file; split a bigger app into files that src/App.jsx imports.
  • One short sentence to the student, then the code. Students are children; keep the words few and kind.

How the student gets it in: BuildLab, the key icon toolbar, Paste or upload code. A whole app (one file or several, each with its path) replaces the project. A fragment with no path and no App component is folded into the existing app by Pal. An HTML page is handed to Pal to convert, so do not send HTML. A student with no project yet uses Upload a project on the start screen instead.

Editing an app the student already has

Ask the student for their current files first. The Code tab has a Copy all files button that gives you every file with its name. Then send back only the files you changed, complete, under the same names. Palstart puts them in next to the files you did not send, and keeps those. It can tell a partial delivery from a whole new app: files that import something already in the project are treated as part of that project. Only send a whole new project when the student is starting fresh or asked you to replace everything.

Giving the student a whole project to download

If your tool can produce files or a zip, that works too. The student uploads the zip, the folder, or the files, and Palstart reads them exactly as it reads a paste. Lay the project out like this, and nothing else:

text
my-app/
  src/App.jsx          the entry, ends with export default App
  src/index.css        optional, loaded automatically
  src/components/...   components, one per file
  src/game/...         game systems, helpers, data

What happens to a repo on the way in:

  • The root folder name and any src/ inside it are stripped, then src/ is put on, so src/App.jsx still imports ./game/engine the way it did on disk.
  • package.json, index.html, main.jsx, vite.config.*, .env, lock files, README, node_modules, dist, .git and anything that is not .js, .jsx or .css are dropped and named in a note. Do not rely on any of them.
  • If there is no src/App.jsx, the file that defines App (or the only component file) becomes it. A main.jsx that mounts the app is not needed and is dropped.
  • Every .css file is merged into the app's stylesheet.
  • TypeScript files come in, but they do not run as they are: Pal rewrites them as JavaScript during debugging. Save everyone the round and write JavaScript.
  • Then the same audit runs and Pal ports the project: one turn that goes through every file and converts whatever cannot run here (TypeScript, npm imports, a router, localStorage, fetch to other sites, env variables, CSS modules), keeping the features and the look. After that the preview starts the app and each error it reports goes back to Pal, up to five rounds, until the preview is quiet. The fewer rules you break, the fewer rounds it takes.

Never tell the student to run npm install, npm run dev, or open a terminal. There is no terminal. The project runs the moment it is uploaded.


A student can give you one link, https://palstart.app/ai/PAL-ABCD-EFGH. It is a plain markdown page with the rules in short, every file of the project they have open, and the ways to send code back, including their code for the connector below. It is always current, so read it again when they say they changed something. It expires with the code.

Sending the code straight into Palstart (the connector)

If you can call tools or URLs, do not make the student carry files. Palstart has a connector: the student opens Connect your AI in BuildLab (paperclip menu, or the start screen) and gives you a code like PAL-ABCD-EFGH. With that code you can read the project they have open and save files straight into it (or, if none is open, start a new project on their dashboard that your later sends update). Files go through the same checks as a paste first; a refusal says what to change, so fix it and send again. Pal debugs them in the preview. With a terminal (Claude Code, Codex, Cursor), open https://palstart.app/ai/<code> and follow its steps: it gives you a small palstart.mjs helper that pulls the project into a folder and pushes it back.

  • MCP (Claude.ai custom connector, Claude Code, Cursor, Codex, Gemini CLI, Windsurf, ChatGPT in developer mode): https://palstart.app/api/mcp, Streamable HTTP, no sign-in. Tools: palstart_docs (this page), palstart_get_project(code) (every file of the open project), palstart_send_files(code, files, note) where files is [{ path, content }].
  • ChatGPT action: OpenAPI at https://palstart.app/api/openapi with getProject and sendFiles.
  • Plain HTTP: GET https://palstart.app/api/push?code=PAL-ABCD-EFGH returns { project: { title, files } }; POST https://palstart.app/api/push with JSON { "code": "PAL-ABCD-EFGH", "files": [{ "path": "src/App.jsx", "content": "..." }], "note": "what changed" }.

Send every file the app needs (or, when editing, every file you changed), complete, with paths like src/App.jsx, src/game/engine.js, src/index.css. At most 80 files, 300 KB each. Tooling files, the HTML shell and package.json are left behind automatically. A code lasts a week and only reaches that one student's BuildLab; the student can replace it at any time.

Putting the project on GitHub

If you are an agent that can run commands (Claude Code, Codex, Cursor, Copilot in a terminal) and the project is on the student's machine, the quickest route is a public GitHub repository. Push it, then give the student the repository link, or the link to the folder that holds src/, like https://github.com/name/my-app or https://github.com/name/my-app/tree/main/app. The student pastes that link into BuildLab (start screen: Upload a project, or the paperclip menu: Paste or upload code) and the files come in from the link, filtered the same way an upload is. One file (/blob/), a raw file and a gist work too. Private repositories do not; nothing else is fetched.

Project structure and imports

A project is any number of files under src/, bundled into one script at run time.

  • src/App.jsx is the entry. It defines function App() and ends with export default App.
  • Files import each other with relative paths: import { update } from './game.js', import Card from '../components/Card'. The extension may be left off; .jsx, .js, index.jsx and index.js are tried in that order. @/foo and src/foo also resolve to src/foo.
  • Named exports, default exports, export { a as b }, export * from, all work. Imports are rewritten by the bundler at the top level only; do not put import inside a function.
  • import './index.css' is allowed and removed. Every .css file in the project is included automatically, src/index.css first, whether or not something imports it.
  • import React, { useState, useEffect } from 'react' is correct and encouraged. In a single-file project the preview also defines useState, useEffect, useRef, useCallback, useMemo, useReducer and useContext as globals, so old code without an import still runs.
  • Importing any npm package (lodash, framer-motion, react-router, axios, three as a package, @react-three/fiber) throws at run time: "nothing from npm is installed in a Palstart app". Write the code yourself or use a global.

The Code tab shows a single-file app as a virtual repo (src/components/Name.jsx, src/backend.js, src/lib/helpers.js, src/constants.js) cut from the one file. When the student copies "all files" to you from such a project, send back either the same virtual files, or one src/App.jsx; both are accepted.


What is loaded in the page

The app runs inside an HTML page Palstart generates. These are already present as globals. Do not import them, do not add script tags, do not load them from a CDN.

GlobalWhat it isLoaded
React, ReactDOMReact 18Always
Tailwind CSSThe full Tailwind utility set, via the browser build. Any class works, including arbitrary values like w-[37px]Always
<iconify-icon>A real HTML element with about 200,000 icons. <iconify-icon icon="lucide:heart" width="20" height="20"></iconify-icon>. Prefer lucide:*, heroicons:*, tabler:*, ph:*. Inherits currentColorAlways
ChartChart.js, as the global Chart (new Chart(ctx, config))When the code mentions new Chart( or Chart.register
THREEthree.js r185 plus the addons listed under 3D, all on the THREE globalWhen the code mentions THREE.
CANNONcannon-es physicsWith three.js
RAPIERRapier 3D physics (compat build)When the code mentions RAPIER
zzfxZzFX sound synth: zzfx(...params)When the code mentions zzfx

Babel transpiles the JSX in the browser, so some newer syntax is not safe. See Syntax rules.

Tailwind extras

Custom animations are defined: animate-fade-in, animate-slide-up, animate-scale-in, animate-shimmer. Use animate-slide-up on cards as they enter, staggered with an inline animationDelay.

Fonts, as Tailwind classes. font-sans is Inter and is the body default. font-display is Space Grotesk, for headings, big numbers and the brand. These load only when a class is used in the code: font-playfair (Playfair Display), font-instrument (Instrument Serif), font-dmserif (DM Serif Display), font-sora, font-outfit, font-bricolage (Bricolage Grotesque), font-manrope, font-bebas (Bebas Neue), font-caveat, font-mono (JetBrains Mono).

The page background is #f8fafc. The root element is #root with min-height: 100dvh.


Syntax rules

The in-browser compiler and the audit enforce these. Breaking one gives the student a blank preview or a warning they cannot fix.

  • No optional chaining ?. and no nullish coalescing ??. Write obj && obj.thing and a || b.
  • No async/await. Use .then() and .catch().
  • Components are declared with function Name() {}, never as arrow functions.
  • .map() callbacks use function (item, i) { return (...); }, not arrows.
  • No component defined inside another component.
  • No template literals (backticks) inside a JSX attribute string. Build the string in a variable first.
  • No emoji anywhere in the UI. Use <iconify-icon>.
  • No dashes used as punctuation in copy (em dash, en dash, or a hyphen doing that job).
  • Close every JSX tag and every parenthesis. The file must parse.
  • Generate ids with a useRef counter seeded above the highest seed id (nextId.current++). Never id: Date.now() or id: list.length.
  • Game loops use requestAnimationFrame with delta time, never setInterval, and the effect cleanup cancels the frame and removes every listener.

Hard rules enforced on every app

These are checked when the code comes back. Code that breaks one is refused or flagged, whoever wrote it.

  • No links out of the app. No href to another site, no window.open, no location.href, no mailto:, no tel:, no form action elsewhere. The runtime also blocks the tap. Every tap stays inside the app.
  • No messaging between people. No chat rooms, DMs, inboxes, comment walls or message boards, whether through appRoom, appData or anything else. Multiplayer game state, scores and names on a leaderboard are fine. Chatting with the AI is fine.
  • No bad language on screen. No curse words, slurs or sexual words in anything the app shows or in its name. Words like "kill", "blood" or "gun" in a game are fine; Pal keeps games at the level of a family adventure film on its own.
  • No API keys in code, and no fetch to outside websites. Outside data comes through callService (below).
  • Images only from allowed sources (below). Any other image host is unreachable from the sandbox and shows as broken.
  • No requesting the microphone or camera on mount. Only after a button press, with the denial caught and shown in the UI.

Extra rules for students under 13

If the student says they are under 13 (or their ask includes the under-13 line), their app also cannot have any of these, and an edit that adds one is refused:

  • Sign-up or login screens, or appAuth at all. Ask for a nickname with appPlayer instead.
  • A password field, an email field, a phone field, a real-name or address field. No personal information of any kind.
  • Device location, camera, microphone, or a file picker.
  • Anything that opens or links to another website, email, a phone call or a text.

The hosted backend

Every app already has a backend. These helpers are defined on window in every preview and every deployed app. They need no import, they all return promises, and they are the only way an app should remember things or know who is here. Never use localStorage for app data, never invent a server, never write sockets.

Put each call in a small named top-level function above the components (function loadScores() { return appData.list('scores', ...); }) and call it from the component with .then. The Code tab files those functions as the app's backend.js, which is where a student looks for "the part that saves".

appPlayer: the player who is here

One record per device, no account, no personal information. Use this for a nickname, best score, level, coins, unlocks and progress.

js
appPlayer.load()                      // -> record or null on a first visit
appPlayer.save({ name, best, level }) // merges fields, creates the record the first time, -> record
appPlayer.id()                        // -> this device's player id (a short string)

Call load() in a useEffect on mount. Greet by name when there is a record; ask for a nickname once when there is not. Call save() when a game ends or a level is cleared, not every frame.

appData: a small database for this app

Shared by everyone who uses the app. Records are plain objects with an id, collection, createdAt, updatedAt, and the fields you saved.

js
appData.list('scores')                                    // array, newest first
appData.list('scores', { orderBy: 'points', order: 'desc', limit: 10 })
appData.list('todos', { where: { done: false } })          // equality on stored fields
appData.list('journal', { mine: true })                   // only this player's own records
appData.get(id)                                           // one record
appData.create('todos', { text: 'Milk', done: false })    // -> saved record with id
appData.create('journal', { text }, { private: true })    // only the signed-in author can read it
appData.update(id, { done: true })                        // merges fields, -> record
appData.remove(id)                                        // -> true
appData.count('posts')                                    // -> number

Limits and rules:

  • Collection names match ^[a-z][a-z0-9_-]{0,39}$ (case-insensitive). player is the collection appPlayer uses; leave it to appPlayer.
  • A record is at most 20 KB of JSON. An app holds at most 20,000 records. list returns at most 200 at a time (default 100); use limit, where and orderBy.
  • mine: true means the signed-in user's records, or, with nobody signed in, the ones made on this device.
  • A record created while signed in belongs to that user and only they can change it. Records made with nobody signed in can be edited by anyone using the app.
  • Keep a leaderboard to one row per player: update their row when they beat their best rather than adding a row per game.

appAuth: accounts inside this app

Accounts that belong to this app only, not Palstart accounts. Use it only when the app truly needs accounts. A game's progress uses appPlayer. Not available to students under 13.

js
appAuth.signup(username, password, profile) // -> { id, username, profile }, keeps the session on the device
appAuth.login(username, password)           // -> { id, username, profile }
appAuth.me()                                // -> current user or null; call on mount
appAuth.logout()                            // -> true
appAuth.updateProfile({ displayName, avatar })
appAuth.isSignedIn()                        // -> boolean, synchronous

Usernames match ^[a-z0-9][a-z0-9._-]{1,31}$. Passwords are at least 4 characters. An app holds at most 2,000 users. Sessions last 30 days. Show the rejection message from a failed login in the UI.

appRoom: two or three people live in one room

Realtime shared state and messages for multiplayer games. A room is a 4-letter code. The host creates it; others join with the code. Loaded only when the code mentions appRoom.

js
appRoom.host({ name })            // -> { code }; this player is the host
appRoom.join(code, { name })      // -> { code }
appRoom.leave()
appRoom.players()                 // -> [{ id, name, isHost, isMe, index }]
appRoom.isHost()                  // -> boolean
appRoom.onPlayers(function (players) {})   // -> unsubscribe function
appRoom.setState({ board, turn }) // merges into shared state and broadcasts it
appRoom.getState()                // -> the shared state object
appRoom.onState(function (state) {})       // -> unsubscribe function
appRoom.send({ type: 'move', x, y })       // broadcast an action to everyone else
appRoom.onMessage(function (msg) {})       // msg has your fields plus from, fromName, at
appRoom.invitedRoom                        // a code that arrived from an invite link, or ''

Pattern: the host owns the game state and calls setState; players send actions with send; everyone renders from onState. Subscribe in a useEffect and call the unsubscribe functions in its cleanup. Game state and names are fine; a chat box is not (see hard rules).

callService: live data from outside

The only way to reach another website. The call goes through Palstart's proxy, which adds the owner's saved API key on the server. Never put a key in code and never fetch an outside URL yourself.

js
callService(serviceId, { path, query, method, body })
// -> promise of the service's own JSON; rejects with a readable message

path starts with / and names an endpoint of that service. query is an object of query parameters. method is GET (default) or POST. body is JSON for a POST.

Free, no key, always available:

idWhat it isExample
open-meteoWeather and 7-day forecasts for any coordinatescallService('open-meteo', { path: '/v1/forecast', query: { latitude: 40.71, longitude: -74.01, current: 'temperature_2m,weather_code,wind_speed_10m', daily: 'temperature_2m_max,temperature_2m_min,weather_code', timezone: 'auto' } })
open-meteo-geoCity name to latitude and longitudecallService('open-meteo-geo', { path: '/v1/search', query: { name: 'Denver', count: 5 } })
frankfurterCurrency exchange ratescallService('frankfurter', { path: '/latest', query: { from: 'USD', to: 'EUR,GBP,JPY' } })
coingeckoCrypto prices (slow down to one call every few seconds)callService('coingecko', { path: '/api/v3/simple/price', query: { ids: 'bitcoin,ethereum', vs_currencies: 'usd', include_24hr_change: true } })

With the student's own key, saved once in BuildLab under Keys (the proxy adds it; the id is all the code needs):

idService
openweathermapOpenWeatherMap
weatherapiWeatherAPI.com
finnhubFinnhub stocks, path: '/api/v1/quote', query: { symbol: 'AAPL' }
alphavantageAlpha Vantage stocks
polygonPolygon.io stocks
newsapiNewsAPI headlines
nasaNASA, path: '/planetary/apod'
virustotalVirusTotal, path: '/api/v3/domains/example.com' or /api/v3/ip_addresses/8.8.8.8
giphyGIPHY, path: '/v1/gifs/search', query: { q: 'happy dog', limit: 12, rating: 'g' }
spoonacularSpoonacular recipes
openaiOpenAI on the student's key, method: 'POST', path: '/v1/chat/completions'
anthropicClaude on the student's key, method: 'POST', path: '/v1/messages'
openrouterOpenRouter on the student's key
my-<name>A service the student added themselves under Keys (any https API with a key in a header or query parameter)

If the key the feature needs is not saved, build the feature anyway and show "Add your <service> key in BuildLab under Keys" in the UI when the call rejects. Call from a useEffect or a button, keep the result in state, show a loading state and the rejection message. Do not fire a call on every keystroke. For the weather of a city, geocode with open-meteo-geo first, then forecast with open-meteo. There is no free stock ticker without a key. For AI features, prefer the built-in endpoint below.

Built-in AI: POST /api/build-ai

Real AI, free for the student, no key. Use it for anything that needs intelligence (a chatbot, a quiz that writes itself, reading a picture, grading an answer, summarising text). Never fake a smart feature with Math.random() or hardcoded answers.

js
function askAI(prompt) {
  return fetch('/api/build-ai', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ prompt: prompt })
  })
    .then(function (res) { return res.json(); })
    .then(function (data) { if (data.error) throw new Error(data.error); return data.result; });
}

Request fields: prompt (string, required, up to 8,000 characters), document (string, up to 120,000 characters, for a long text to analyse; keep the question in prompt), image (a data:image/...;base64,... URL to look at), audio (a data:audio/...;base64,... URL to listen to), search: true (answer with live web search), max_tokens (64 to 3,000; default 500, or 1,500 with a document).

Response: { result: string }. A request that broke the child-safety rules returns { result: <a kind refusal>, refused: true } with status 200; show it as the answer. Errors come as { error: string } with a 4xx or 5xx status.

Build structured answers by asking for them in the prompt ("Answer with JSON only: {\"question\": ..., \"options\": [...], \"answer\": ...}") and parsing result with a try/catch fallback.

Images: /api/build-image

One URL for every picture, usable straight in an <img src>:

  • A real photo: /api/build-image?q=golden retriever puppy&i=0&w=800&h=600. q is 1 to 4 words naming what is in the photo, never a UI word like "hero" or "background". i picks the nth match, so give every card in a list its own index. w and h are the rendered size. Add object-cover to the <img>.
  • Generated artwork: /api/build-image?prompt=flat vector logo of a smiling water drop, no text&style=logo&w=512&h=512. style is one of logo, icon, flat, illustration, 3d, pixel, watercolor, photo. A new prompt takes about ten seconds and costs money the first time, then is cached forever. Keep prompts stable between edits; never generate on every render or keystroke. Show a bg-gray-100 animate-shimmer box while it loads.
  • An app whose feature is image generation: add &json=1 and call it from the user's action; the response is { url }. Each caller gets about 12 fresh generations an hour; cached prompts are free.
  • Avatars: https://api.dicebear.com/9.x/{style}/svg?seed={name} with style avataaars, bottts, identicon, shapes or initials.
  • The student's own uploads: a URL under public.blob.vercel-storage.com/images/uploads/, used exactly as given.

Nothing else is reachable: no Unsplash, no placeholder services, no loremflickr, no made-up CDN paths, no picsum.


Layout rules

A project has a target: mobile (previewed at 390 pixels wide, deployed as a phone web app) or web (full browser width). The student's ask usually says which; if not, match the existing code.

Mobile:

  • Root is flex flex-col h-dvh (never h-screen). Header and bottom nav are plain flex children (shrink-0), never fixed. Only <main className="flex-1 overflow-y-auto"> scrolls.
  • One column. At most grid-cols-2 for stats. No md: or lg: grid variants.
  • No fake phone status bar, no max-w-sm phone silhouette, no hover-only actions.
  • Tap targets 44 pixels or more. Every input, textarea and select uses text-base (iOS zooms into anything smaller).
  • px-4 side padding and pb-6 at the end of the scrolling area.

Web:

  • A full-width header (top nav bar) or a left sidebar, then a centered max-w-5xl or wider container with a responsive grid.
  • No bottom tab bar, no fake phone chrome, no narrow single column.

Both: a real header, neutral white and gray with one accent color used sparingly, cards with border border-gray-100 shadow-sm at most, font-display for headings and big numbers, real icons from Iconify, no emoji, no marketing phrases.


Games

2D canvas games

The code is run and played by a checker before the student sees it. This shape passes:

  • All game values live in one ref: const game = useRef({ state: 'start', score: 0, best: 0, keys: {}, player: {...}, enemies: [], t: 0 }). The loop reads and writes game.current only. React state is only for the HUD, pushed at most four times a second.
  • One useEffect with [] owns everything: sizes the canvas, adds listeners, starts requestAnimationFrame, and its cleanup cancels the frame and removes every listener.
  • frame(ts) computes dt = Math.min(0.05, (ts - last) / 1000), calls update(dt) then draw(), and requests the next frame. Every speed is per second, multiplied by dt. The loop runs in every state; update only moves things while state === 'playing'.
  • Input: keydown sets game.current.keys[e.code] = true, keyup clears it, update reads the map. Use e.code names (ArrowLeft, Space, KeyW) consistently. Prevent default on arrows and space. On-screen buttons (56 pixels or more, onPointerDown/onPointerUp) set the same keys map, so it plays on a phone.
  • Three states: start (title, controls, Start button, "press Space"), playing, over (score, best, Play again). Restart resets game.current in place, never reloads.
  • Difficulty rises gently with a cap. Spawn away from the player. Sound through zzfx only from input and events, never on mount.
  • Canvas sizing from the container with devicePixelRatio, drawing in a logical world size (say 800 by 450) scaled to fit.
jsx
// filename: src/App.jsx
import React, { useState, useEffect, useRef } from 'react';

function App() {
  const canvasRef = useRef(null);
  const game = useRef({ state: 'start', score: 0, best: 0, keys: {}, player: { x: 100, y: 200, vy: 0 }, obstacles: [], t: 0 });
  const [hud, setHud] = useState({ state: 'start', score: 0, best: 0 });

  useEffect(function () {
    var canvas = canvasRef.current, ctx = canvas.getContext('2d'), W = 800, H = 450, raf = 0, last = 0, hudAt = 0;
    function fit() {
      var r = canvas.parentElement.getBoundingClientRect(); var dpr = window.devicePixelRatio || 1;
      canvas.width = Math.floor(r.width * dpr); canvas.height = Math.floor(r.height * dpr); canvas.style.height = r.height + 'px';
      ctx.setTransform(dpr * r.width / W, 0, 0, dpr * r.width / W, 0, 0);
    }
    function reset() { var g = game.current; g.state = 'playing'; g.score = 0; g.t = 0; g.player = { x: 100, y: 200, vy: 0 }; g.obstacles = []; }
    function onKey(down) {
      return function (e) {
        if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].indexOf(e.code) >= 0) e.preventDefault();
        game.current.keys[e.code] = down;
        if (down && (e.code === 'Space' || e.code === 'Enter') && game.current.state !== 'playing') reset();
      };
    }
    function update(dt) { var g = game.current; if (g.state !== 'playing') return; g.t += dt; /* move, spawn, collide; on death: g.state = 'over'; g.best = Math.max(g.best, g.score); */ }
    function draw() { var g = game.current; ctx.clearRect(0, 0, W, H); /* world, player, HUD; title or game-over overlay by g.state */ }
    function frame(ts) {
      var dt = Math.min(0.05, (ts - (last || ts)) / 1000); last = ts; update(dt); draw();
      if (ts - hudAt > 250) { hudAt = ts; var g = game.current; setHud({ state: g.state, score: g.score, best: g.best }); }
      raf = requestAnimationFrame(frame);
    }
    var kd = onKey(true), ku = onKey(false);
    fit(); window.addEventListener('resize', fit); window.addEventListener('keydown', kd); window.addEventListener('keyup', ku);
    raf = requestAnimationFrame(frame);
    return function () { cancelAnimationFrame(raf); window.removeEventListener('resize', fit); window.removeEventListener('keydown', kd); window.removeEventListener('keyup', ku); };
  }, []);

  return (
    <div className="h-dvh flex flex-col bg-gray-900 text-white">
      <div className="flex-1 relative"><canvas ref={canvasRef} className="absolute inset-0 w-full h-full" /></div>
      <div className="shrink-0 p-4 flex items-center justify-between font-display">
        <span>Score {hud.score}</span><span>Best {hud.best}</span>
      </div>
    </div>
  );
}

export default App;

Grid games (Snake) step on a timer accumulated from dt. Quizzes and puzzles need no canvas; keep the ref-owned state, the single effect and the three states anyway.

3D games with three.js

THREE is a global at r185. Do not import three. These addons are on the THREE global by name: PointerLockControls, OrbitControls, FlyControls, GLTFLoader, DRACOLoader, HDRLoader, RGBELoader, FontLoader, Font, TextGeometry, ConvexGeometry, RoomEnvironment, Sky, Water, Reflector, Lensflare, LensflareElement, GroundedSkybox, CSS2DRenderer, CSS2DObject, CSM, Octree, Capsule, ImprovedNoise, SimplexNoise, MeshSurfaceSampler, mergeGeometries, mergeVertices, EffectComposer, RenderPass, OutputPass, UnrealBloomPass, SMAAPass, GTAOPass, BokehPass, FilmPass, OutlinePass, GlitchPass, AfterimagePass, RenderPixelatedPass, cloneSkeleton. Plus two helpers: THREE.makeGLTFLoader() (a loader with DRACO wired up; always use it instead of new THREE.GLTFLoader()) and THREE.ASSETS.

  • Names removed from three.js do not exist: no Geometry, no *BufferGeometry suffix, no sRGBEncoding, no outputEncoding, no THREE.Math. Use renderer.outputColorSpace = THREE.SRGBColorSpace and texture.colorSpace = THREE.SRGBColorSpace.
  • Build the scene in one useEffect with [], keep three.js objects in refs, never in useState, never setState every frame.
  • Cleanup cancels the frame, calls renderer.dispose(), removes the canvas and any CSS2DRenderer element, and removes every listener. Without this each preview reload leaks a WebGL context and the game goes black after about 16.
  • Movement is multiplied by clamped dt. The world is built from primitives first and playable before any model finishes loading.
  • MeshStandardMaterial or MeshPhysicalMaterial for real surfaces, a DirectionalLight with castShadow as the key light, ambient as fill only.
  • Models, textures, skies and sounds load only from these hosts: https://cdn.jsdelivr.net/gh/mrdoob/three.js@r185/examples/... (the three.js example assets), https://cdn.jsdelivr.net/gh/KhronosGroup/glTF-Sample-Assets@main/Models/..., and https://dl.polyhaven.org/file/ph-assets/.... Any other host fails. Do not guess file names; a wrong path is a blank world.
  • Pointer lock only on a click, sound only after a click, controls explained on the title screen, an objective, a fail state and a restart that does not reload.
  • TWEEN, gsap and Stats are not loaded; animate by hand with dt or THREE.MathUtils.damp.

How the student puts your code back

  1. In BuildLab, with their project open, the student clicks the key icon in the toolbar under the chat and chooses Paste or upload code.
  2. If you have the Palstart connector or action, you send the files yourself with the student's code (see Sending the code straight into Palstart) and they appear in BuildLab. Otherwise they paste your whole answer, upload the files (a zip, a whole project folder, or single files), drag them onto BuildLab, or paste a GitHub link to a public repository, a folder in one, a file, or a gist. The parser finds every file by its // filename: line or its ### path heading, and keeps the paths. Uploaded and fetched files keep their folder structure under src/, with the project's root folder and any src/ inside it stripped.
  3. With "Let Pal debug it once it is in" ticked (the default), Pal first ports the whole project to Palstart, then fixes whatever the preview reports, round by round.
  4. A whole app (an App component, one or more files) replaces the project. A fragment is folded into the existing app. Config files, server files, test files (*.test.js, setupTests.js, reportWebVitals.js), lockfiles and the HTML shell are left behind and named in a note; do not spend effort on them.
  5. The code goes through the same audit the builder's own code gets. Rule breaks come back as a note the student will show you; a syntax error or a missing App is a warning before the preview goes blank.
  6. The preview reloads with the new code. Run-time errors appear in the preview as red text with a stack trace pointing at the file and line.
  7. Every running app keeps its own log (console output, errors, failed loads and failed requests). Copy logs in BuildLab's toolbar and error bar, under any error screen, and on the bar at the bottom of a published or Showcase app, copies it as text with the app's name, browser and file list. A student can paste that straight to you; treat it as ground truth about what happened at run time.

Students can also edit one file at a time on the Code tab (Edit, New file) and copy any file or all files to you with their names.

If the student shows you an error, it is ground truth. Common ones: X is not defined (an import of a package that does not exist here, or a hook used without the global), The screen is blank: the app rendered nothing visible, src/App.jsx does not export an App component, imports "...", which is a package, and nothing from npm is installed, Links to other websites are off in Palstart apps.


A complete small example

A mobile to-do app with saved data, an icon, and a real AI feature, in one file.

jsx
// filename: src/App.jsx
import React, { useState, useEffect } from 'react';

function loadTodos() { return appData.list('todos', { orderBy: 'createdAt', order: 'asc' }); }
function addTodo(text) { return appData.create('todos', { text: text, done: false }); }
function toggleTodo(todo) { return appData.update(todo.id, { done: !todo.done }); }
function removeTodo(id) { return appData.remove(id); }
function suggestTodo(existing) {
  return fetch('/api/build-ai', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ prompt: 'Suggest one short, useful to-do for a student. Their list already has: ' + existing.join(', ') + '. Answer with the to-do text only.' })
  }).then(function (res) { return res.json(); }).then(function (data) { return data.result; });
}

function TodoRow(props) {
  return (
    <div className="flex items-center gap-3 bg-white rounded-xl p-4 border border-gray-100 shadow-sm animate-slide-up">
      <button onClick={props.onToggle} className="w-11 h-11 flex items-center justify-center rounded-lg bg-gray-100 text-gray-500" aria-label="Toggle">
        <iconify-icon icon={props.todo.done ? 'lucide:check-circle-2' : 'lucide:circle'} width="22" height="22"></iconify-icon>
      </button>
      <span className={props.todo.done ? 'flex-1 line-through text-gray-400' : 'flex-1 text-gray-900'}>{props.todo.text}</span>
      <button onClick={props.onRemove} className="w-11 h-11 flex items-center justify-center text-gray-400" aria-label="Delete">
        <iconify-icon icon="lucide:trash-2" width="20" height="20"></iconify-icon>
      </button>
    </div>
  );
}

function App() {
  const [todos, setTodos] = useState([]);
  const [text, setText] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  useEffect(function () {
    loadTodos().then(setTodos).catch(function (e) { setError(e.message); });
  }, []);

  function submit() {
    var t = text.trim();
    if (!t) return;
    setText('');
    addTodo(t).then(function (rec) { setTodos(todos.concat([rec])); }).catch(function (e) { setError(e.message); });
  }

  function suggest() {
    setBusy(true);
    suggestTodo(todos.map(function (x) { return x.text; }))
      .then(function (idea) { setBusy(false); setText(idea || ''); })
      .catch(function () { setBusy(false); setError('Could not get a suggestion. Try again.'); });
  }

  return (
    <div className="h-dvh flex flex-col bg-gray-50">
      <header className="shrink-0 bg-white border-b border-gray-100 px-4 py-4">
        <h1 className="font-display text-2xl font-bold text-gray-900">Today</h1>
        <p className="text-sm text-gray-500">{todos.filter(function (x) { return !x.done; }).length} to go</p>
      </header>
      <main className="flex-1 overflow-y-auto px-4 py-4 space-y-3 pb-6">
        {error && <div className="text-sm text-red-600">{error}</div>}
        {todos.map(function (todo, i) {
          return <TodoRow key={todo.id} todo={todo}
            onToggle={function () { toggleTodo(todo).then(function (rec) { setTodos(todos.map(function (x) { return x.id === rec.id ? rec : x; })); }); }}
            onRemove={function () { removeTodo(todo.id).then(function () { setTodos(todos.filter(function (x) { return x.id !== todo.id; })); }); }} />;
        })}
      </main>
      <div className="shrink-0 bg-white border-t border-gray-100 p-4 flex gap-2">
        <input value={text} onChange={function (e) { setText(e.target.value); }} onKeyDown={function (e) { if (e.key === 'Enter') submit(); }}
          placeholder="Add something" className="flex-1 text-base px-4 py-3 rounded-lg border border-gray-200" />
        <button onClick={suggest} disabled={busy} className="w-12 h-12 flex items-center justify-center rounded-lg bg-gray-100 text-gray-600" aria-label="Suggest">
          <iconify-icon icon="lucide:sparkles" width="20" height="20"></iconify-icon>
        </button>
        <button onClick={submit} className="px-5 rounded-lg bg-gray-900 text-white font-semibold active:scale-[0.98]">Add</button>
      </div>
    </div>
  );
}

export default App;

Checklist before you answer

  • Every changed file is complete, with // filename: src/... as its first line or a ### src/... heading above it.
  • Plain JS and React 18 JSX. No TypeScript. No ?., ??, async/await, arrow components, arrow .map callbacks, nested components, emoji, or backtick strings inside JSX attributes.
  • Only react is imported from a package. Everything else is a global or a relative file.
  • No package.json, index.html, main.jsx, server, or config file.
  • Data and accounts go through appPlayer, appData, appAuth, appRoom. Outside data through callService. AI through /api/build-ai. Images through /api/build-image, DiceBear or the student's uploads.
  • No links out, no messaging between people, no real guns or killing, no API keys, no outside fetch.
  • Mobile apps use the h-dvh flex column with text-base inputs; web apps use the full width.
  • Game loops use the ref-owned state, one effect, dt, a keys map, three states and a restart.
  • One short sentence to the student, then the code.