# Spar, for agents This file is everything an agent needs to write a Spar app. It is put together by `bun run llms` from this guide, the principles, the API reference, the recipes and the source of the showcase app, so the examples are code that is built and tested, not sketches. When this file and the code disagree, the code is right and this file is stale: run `bun run llms`. ## What Spar is Spar is a UI framework for people who are all in on Effect. It is not general purpose and does not try to be. A Spar app is an Effect program front to back: components are Effects, state lives in Schema-described stores, the backend is an Effect RPC group, and one trace follows a click from the page through the backend and back. The framework sees every state change and every backend call, logs each one, and shows them in devtools that people use in the page and agents use over MCP or from a shell. If a thing can be done two ways, Spar picks one and refuses the other, at compile time or at build time. Do not look for the escape hatch. There is not meant to be one. ## Read this first "Routes, data and no waterfalls", the part right after this guide, is the one way to load data: declare a query, ask for it in the component that needs it, pass values down as reactive props. Never fetch in a component's Effect and never wait there. Three rules that break the build most often: 1. Never write a bare `(props) => ...` as an enhancer inside `compose`. Wrap it: `withEffectProps((props) => Effect.gen(...))` when it runs an Effect, `withHandlers((props) => ({ ... }))` when it returns plain values. A bare one makes `props` `unknown` in every enhancer after it (`TS18046`), and the errors that follow (`TS2339`, an `Effect` that is not a `Handler`) all go away with the wrap. 2. A UI write (`UiState.set`, `UiState.update`) is not an Effect, so `Effect.all`, `Effect.andThen`, `Effect.tap` and `Effect.forEach` do not take it (`TS2739: Type 'UiWrite' is missing the following properties from type 'Effect'`). Yield it inside `Effect.gen`, or give a handler a list of actions: `onReset: [UiState.set(props.name, ""), UiState.set(props.open, false)]`. 3. A handler (an event prop, a `withKey` action) takes an `Effect` with no error and no requirement, a UI write, or a list of them. A store command (`store.commands.added(payload)`) already fits. Something that fails or needs a service gets handled first: `Effect.catch`, or provide it. When what to run depends on a value, return the action from an Effect instead of yielding it: an action (a callback prop's result, a list) cannot be yielded, and Spar runs what you return. `onEnter: Effect.gen(function* () { const now = yield* props.palette.get; return props.onRun(now.active) })`. Returning nothing runs nothing. ## The shape of an app ``` src/ api.ts the RPC contract shared with the backend: groups, payloads, errors routes.ts Router.route(path, Schema) values SomeStore.ts Store.Tag: state Schema, actions, selectors Some.tsx components: compose(...enhancers)((props) => ) main.ts App.mount with the layers server/ what runs on the server, or stands in for it server/ the backend's handlers ``` A component is one expression: `compose(...enhancers)((props) => )`. The enhancers add props (a store's values and commands, UI state, a query, a key press); the view comes last, inline, and its props are inferred from them. The view never runs an Effect; an enhancer never writes markup. Child components are written in JSX inside the view. Your own behaviour, written inside `compose`, is `withEffectProps((props) => effect)` for props made by an Effect or `withHandlers((props) => values)` for plain values. Written as a named function, give its parameter a type: `const withDraft = (props: { readonly id: string }) => Effect.succeed({ ... })`. A group of enhancers is `compose(...)` without a view. `compose` takes up to 10 enhancers; group some with `compose(...)` beyond that. If TypeScript says `'props' is of type 'unknown'` or that a property you added does not exist, an untyped inline function among the enhancers is the cause (the build says so too, with `SPAR_ENHANCER_UNTYPED`): wrap it in `withEffectProps` or `withHandlers`. Three other errors to avoid: - `For` and `Show` are imported from `"spar"` like everything else. - In a `.tsx` file a generic arrow is read as a JSX tag: write `(item: A) => ...` with the comma, or use a `function`. - `exactOptionalPropertyTypes` is on: never pass `undefined` to an optional prop or attribute. Leave it out (`{...(title === undefined ? {} : { title })}`) or give a value (`title ?? ""`). `For` reads its item type from `each`. When `each` is an inline expression such as `Reactive.map(props.rows, (all) => all.filter(...))`, TypeScript cannot infer it; compute the list in an enhancer and pass `props.shown` instead. ## The one way to do each thing | You want to | Do this | Not this | | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | Make a component | `compose(...enhancers)((props) => )` in a `.tsx` file | A plain function returning JSX | | Take props from the parent | `withProps({ name: Schema })` as the first enhancer | Untyped props | | Make props with an Effect | `withEffectProps(Effect.fnUntraced(function* (props) { ... return { ... } }))` | `(props) => Effect.gen(...)` written inline among enhancers: every enhancer after it sees `props` as `unknown` | | Read a store | `withStore(Store, (store) => ({ count: store.select.count, onAdd: store.commands.added() }))` | Reading a store inside the view | | Hold state only the screen cares about | `withUiState(name, Schema, initial)` | `Ref`, `SubscriptionRef`, `let`, a module variable | | Add a behaviour of your own | A named function with a typed parameter, `(props: { readonly id: string }) => Effect.succeed({ ... })`, or `compose(a, b)` with no view | Copying the same enhancers into every component; an untyped inline function among enhancers | | Use a child component | Write it in JSX in the view: `` | Passing elements down as props | | Hold data the app cares about | A `Store.Tag` with actions and selectors | UI state seeded from a store, a service with a Ref | | Put a store where one component uses it | `SomeStore.with(Component)`, then mount the result | Wiring a layer at the root for a store one screen owns | | Share a store across the app | `SomeStore.layer` in the layers given to `App.mount` | A global | | Change app state | `store.commands.(payload)` | Writing to state anywhere else | | Change UI state | `UiState.set` or `UiState.update` in a handler | Writing UI state from a command, a stream or a service | | Show a list | ` item.id}>{(item) =>
  • ...
  • }
    ` | `.map` inside JSX | | Show a tree (a component inside itself) | `const Row: View.Component = compose(...)(... ...)`, a `Schema.suspend` Schema | Flattening the tree by hand; leaving the type off | | Show one thing or another | `...` | A ternary inside JSX | | Load data from the server | A `Query.Tag`, and `withQuery(name, TheQuery, (props) => input)` where it is needed | Fetching in a component and passing the result down | | Use loaded data in an action | An Effect that reads `TheQuery.read(input)` and then sends a command with the result | Props or arguments that carry server data | | Stop a second run while one is going | Run the work with `FiberHandle.run(handle, effect, { onlyIfMissing: true })` | Disabling the button and hoping nothing else starts it | | Run a flow with a wait in it | One Effect: a command, `Effect.sleep` or the call, a command with the result | A lock, a queue, a flag in UI state | | Call your backend | `Backend.rpc(Group, url)` and call the client | `fetch`, axios, tRPC, a hand-rolled client | | Call someone else's HTTP API | An Effect `HttpClient` call, or an HttpApi client, with `Backend.layer` provided | `fetch`, `FetchHttpClient.layer` | | Send something that must not be lost | `Outbox.channel(name, schema, send)`: saved on the device, retried with an idempotency key | Calling the server from a handler and hoping | | Keep a store across a reload | `SomeStore.layerSaved`, with a `KeyValueStore`; other tabs that save it are followed | Writing to `localStorage` by hand | | Handle a failure a component can have | `View.recover(ErrorSchema, FallbackView)` | `catchAll` that hides it; leaving it (compile error) | | Show something while a component loads | `View.pending(LoadingView)` | A loading flag in UI state | | Navigate | `Router.route(path, Schema)`, `router.link(route, params)`, `router.go(route, params)` | `location.href`, string paths | | Build a form | `Form.make(Schema, initial)`, `form.field(name)`, `form.submit` or `form.submitThen` | UI state for each input plus hand validation | | React to a key press | `withKey("Escape", (props) => UiState.set(props.open, false))` | `addEventListener` | | Run something while mounted | `withEffect((props) => effect)`; `Events.onWindow` / `onDocument` inside it | A module-level listener | | Focus or measure an element | `const input = yield* Handle.make` (an Effect, not a function), passed as a `Props.Handle` | `document.querySelector` | | Open a dialog, menu, popover or tooltip | The ones in `@spar/ui`, or `View.portal` with `Overlay` | A positioned div | | Note something that happened, for the log | `Timeline.note(kind, name, detail)` | `console.log` | | Test a store | Provide its layer and call commands in `it.effect` | Mounting a page to test a reducer | | Test a component | `spar/testing`: `Testing.mount`, then find and click by role | Reaching into nodes by class name | ## What is refused, and why Compile errors (the proofs are the files in `apps/demo/forbidden`, each of which must fail to compile): - A component from a plain function, a view without a Schema for its props, UI state, a store, a selector or route params without a Schema. Everything declared has a Schema so the devtools and agents can read it as data. - A component whose Effect needs a service nobody provided, or can fail with an error nobody recovers, mounted anyway. Needs and failures are settled at mount. - A backend error from the shared contract that the component does not handle. - A reducer returning an object literal with a literal-typed field needs its return type written (`(state: State): State => ...`), or TypeScript widens the literal and the action is rejected. - UI state made in a service, written from a command, a stream or a service listener, or seeded from a store. UI state belongs to one component and changes only in its handlers. - A component that can still fail, written as a JSX tag (`TS2604` / `TS2786`: "cannot be used as a JSX component"). Recover its error inside it with `View.recover`, or mount it with `View.child(component, props)` from an enhancer. If its error type shows as `unknown`, look for the first error in that component instead: something there was not typed. - A service passed into a view, a modal outside a portal, `View.pending` placed before `View.recover`, a route mounted with the wrong page. Build errors (the Vite plugin stops the build and names the file, line and rule): - `views-need-a-schema`: JSX outside `View.make`. - `jsx-only-in-views`: JSX inside an expression or a call, such as `.map` or a ternary in a hole. - `no-effect-run-in-views`: `Effect.run*` in a view file. - `state-only-through-spar`: `Ref.make`, `SubscriptionRef.make`, `SynchronizedRef.make`, `MutableRef.make`, `TxRef.make`, `let`, `var`. State the framework did not make is state the log cannot show and the devtools cannot rewind. - `backend-only-through-spar`: `fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`, `sendBeacon`, `FetchHttpClient.layer`, and imports of axios, ky, got, superagent, graphql-request, openapi-fetch, `@trpc/client`, `@apollo/client`, socket.io-client. A call the framework did not make is a call missing from the trace. The two `-through-spar` rules look at app source. They skip `node_modules`, tests, config files, `scripts/` and any `server/` folder (server code is not page state). House rules the linter holds everywhere: no loops, no mutation, no comments, no casts, `type` not `interface`, no nested ifs. ## UI state and app state UI state is what one component remembers about its own screen: a menu is open, what was typed, which tab is showing. It is made with `UiState.make` in that component's Effect, lives in one tree by component path, and goes away when the component unmounts. Nothing else can write it. App state is what the app knows: the agents, the notes, the cart. It lives in a store. A store is a Schema for the state, named actions with pure reducers, and named selectors. It changes only through `store.commands.(payload)`, and every command is an entry in the store's log. Keep in the state only what cannot be worked out from the rest. A total, a count, a "has any", a filtered or sorted list is a selector over the state, never a field that every reducer has to remember to update: `total: Store.selector(Schema.Int, (state: State) => state.counts.reduce((sum, c) => sum + c.count, 0))`. A second copy of a value is a value that can disagree with the first. A store does not have to be declared at the root. `SomeStore.with(Component)` makes one unit of a store and the component that uses it. Mount that unit twice and there are two stores, each with its own state, each registered in the same root registry the devtools read. So it is still model, view, update: one registry, one log, every change an action. It only does not look like it, because the store and its view sit in the same file. ## Flows and server data Read the "State, events that interleave, and server data" part below before writing any store with async work. The short version: - A store accepts every command; there are no guards. Work that takes time is an Effect on a service (or an enhancer): it sends a command, does the work, and sends a command with the result. Every command is in the log and the trace. - Server data is a `Query.Tag`. Views never fetch and props never carry server data: an Effect that needs it reads `TheQuery.read(input)` itself. - When only the newest run matters (a search box, a filter), run it with `FiberHandle.run(handle, effect)`, which stops the one before; or load it with a Query. - When a second press must not start the work again (Pay, Save, Send), run it with `FiberHandle.run(handle, effect, { onlyIfMissing: true })`, which ignores the repeat. - To change one row of a long list in a reducer, return `Store.withRow(state.rows, index, row)`: the list rewrites that row only. - A query's `value` is null while a new input loads. To keep the last rows on screen while the next page or filter loads, show the handle's `latest`; for "load more", use `TheQuery.pages`. - A query with no input is asked for with no argument, `yield* TheQuery.ask()`. Giving it an input, such as one made from another query's value, does not compile (`SPAR_NEEDLESS_WAIT`). - A draft the user is typing is never overwritten with a saved or loaded value. Keep both. - Spar reports two timing mistakes while the app runs (`SPAR_DUPLICATE_CALL`, `SPAR_TYPING_REPLACED`). After a change, run the app and read the log for `noticed` and `waited` entries; each names its fix. - A store's layer needs no `SecureRandom` from you. A UI write (`UiState.set`, `update`) can be yielded inside `Effect.gen`. Give every reducer its state type: `(state: State, payload) => ...`. - A form field's problem is shown by `TextField`, `Select` and `Checkbox` with the role `alert`. ## The backend Declare the contract once, in a file both sides import: ```ts export class Agents extends RpcGroup.make( Rpc.make("Describe", { payload: { name: Schema.String }, success: Started, error: NoRecord, }), Rpc.make("Start", { payload: { name: Schema.String, idempotencyKey: Schema.String }, error: ServerUnreachable, }), Rpc.make("Started", { success: Schema.Array(Schema.String) }), Rpc.make("Users", { success: Schema.Array(User) }), Rpc.make("Lookup", { payload: { kind: Schema.String, id: Schema.String }, success: Found }), ) {} ``` (`apps/sidebar/src/api.ts`) On the page, `Backend.rpc(Agents, url)` gives a typed client. Its calls are spans in the trace of whatever caused them, the trace context travels to the backend in the request, and the backend's spans join the same trace. Provide `Backend.layer` once, where the app is mounted. ## Devtools `sparDevtools({ backends })` from `spar/devtools/vite` adds the tools on the dev server only. In the page they give the inspector, the one log with rewind, step and fork, the trace waterfall across page and backend, and the stores with their outbox. No collector has to run to see a trace. An agent gets the same over MCP (`bun run --filter @spar/devtools-mcp start`, then connect to `http://127.0.0.1:4188/mcp`) or from a shell (`bun run --filter @spar/devtools-mcp cli call ''`). A useful loop when debugging: 1. `get_timeline` to see what happened, in order. 2. `step` with `by: -1` to walk back; each answer has the moment and the spans it caused. 3. `diff_states` to see what an action changed in a store. 4. `fork`, then `run_action` or `set_ui_state` to try something else from that point. 5. `switch_branch` with `branch: 0` to return to what really happened. ## Working in this repo - `bun run showcase` starts the showcase app, its backend and the devtools. - `bun run check` is everything that must pass: format, lint, types, tests with 100% coverage, the forbidden-code proofs, the production build check. - `bun run bench` reruns the benchmarks and rewrites `docs/benchmarks.md` and `docs/benchmarks.html`. - Browser suites are moon tasks: `bun run moon run sidebar:features sidebar:walkthrough sidebar:devtools sidebar:traced demo:browser stories:play ssr:browser --concurrency 1`. - Only run tools through package scripts or moon tasks. # Routes, data and no waterfalls The short version: declare the data a component needs in that component, pass values down as props the way you always would, and Spar loads everything that can load at once. You do not write loaders, fragments or lists of dependencies. ### Start here: a prop from a store, a query that uses it A parent reads a value from a store and passes it to a child. The child declares a query that uses the prop. ```tsx export class OrdersQuery extends Query.Tag()("shop/Orders", { input: Schema.Int, success: Schema.Array(Order), failure: ServerUnreachable, load: (userId: number) => Effect.flatMap(Effect.service(Server), (found) => found.orders(userId)), staleAfter: "30 seconds", }) {} ``` (`packages/spar/test/serverData.test.tsx`) ```tsx export const Orders = compose( withProps({ userId: Props.Reactive(Schema.Int) }), withQuery("orders", OrdersQuery, (props) => props.userId), )((props) => (

    {props.orders.status}: {Reactive.map(props.orders.value, (all) => all?.length ?? 0)} orders

    )) ``` (`packages/spar/test/serverData.test.tsx`) ```tsx export const Parent = compose( withStore(PeopleStore, (people) => ({ selected: people.select.selectedId })), )((props) => ) ``` (`packages/spar/test/serverData.test.tsx`) That is the whole of it. Provide `OrdersQuery.live` where the app is mounted and it works. What Spar does with it: 1. `ask` (which `withQuery` calls) returns at once with a handle: `status`, `value`, `error`, `loading`, each a reactive value, and `refetch`. No enhancer waits for data. 2. Because nothing waits, the parent goes straight on to draw its children, and they draw theirs. Every query in the tree is reached in one pass, and every query with an input starts then, together. 3. The query runs in its store, which lives at the root. The component can unmount and the answer still arrives and is kept. Two components that ask for the same input share one request. 4. When the prop changes, the query for the new value starts. An input that was loaded recently enough (`staleAfter`) is shown from the cache with no request. A query that needs another query's answer takes its input from that answer: ```tsx const ReportPage = compose( withProps({ params: Props.Reactive(Report) }), withQuery("report", ReportQuery, (props) => Reactive.map(props.params, (now) => now.report)), withQuery("author", AuthorQuery, (props) => Reactive.map(props.report.value, (found) => Option.fromNullishOr(found?.authorId)), ), )((props) => (

    {Reactive.map(props.report.value, labelOf)}

    {props.report.status}

    Written by{" "} {Reactive.map(props.author.value, labelOf)}{" "} {props.author.status}

    )) ``` (`apps/sidebar/src/DeepPage.tsx`) While the input is none the author query is `waiting`. The moment the report answers, it starts. That is the only waterfall Spar allows, it is the one the data really has, and it shows: as the `waiting` status, and in the trace, where the author's request says "input from Report . value". The one rule: pass a changing value down as the reactive value it is (`Props.Reactive`), which is how Spar passes changing values anyway. If you read it out into a plain number first, the child's query cannot follow it when it changes. ### Routes A route is a path and a Schema. Fields named in the path are path params; every other field is a search param. Links and navigation take the decoded params, so a wrong param is a type error. ```ts export const orgRoute = Router.route("/org/:org/*", Org) ``` (`apps/sidebar/src/Deep.ts`) A link is `router.link(route, params)`, with the params typed by the route's Schema. A route inside another is declared under it, so its path is written once. The parent must end with `/*`, and the Schema must carry every param of the whole path; both are compile errors otherwise: ```ts export const teamRoute = Router.under(orgRoute, "/team/:team/*", Team) ``` (`apps/sidebar/src/Deep.ts`) ```ts export const memberRoute = Router.under(teamRoute, "/member/:member/*", Member) ``` (`apps/sidebar/src/Deep.ts`) Segments nest with open-ended routes and an outlet in each layout. `Router.live` keeps a layout mounted while only its params change and gives it the params as a reactive value, which is what a query wants as its input. In the showcase each segment asks for its own data from its params and places the next segment's outlet: ```tsx const withInner = ( route: Router.Route, page: View.Component<{ readonly params: Reactive.Reactive }, never, R>, ) => () => Effect.map( Router.outlet({ routes: [Router.live(route, page)], otherwise: DeepMissingView }), (inner) => ({ inner }), ) ``` (`apps/sidebar/src/DeepPage.tsx`) ```tsx export const OrgSegment = compose( withProps({ params: Props.Reactive(Org) }), withSegment("Organisation", OrgQuery, (now: typeof Org.Type) => now.org), withInner(teamRoute, TeamSegment), )(SegmentView) ``` (`apps/sidebar/src/DeepPage.tsx`) There is no separate route tree to keep in step: the nesting is the outlets, and the paths follow from `under`. A page five segments deep written this way starts all five segments' requests together. The showcase has one (`apps/sidebar/src/Deep.ts`), and its browser check reads the backend's own spans and fails if the five do not start together or if the sixth does not wait for the one it needs (`apps/sidebar/scripts/deep.ts`). ### Preload on intent A link has `onIntent`. Put it on the anchor (`onPointerenter={link.onIntent}` and `onFocus={link.onIntent}`, beside `href={link.href}` and `onClick={link.onClick}`) and pointing at the link, or focusing it, starts the target page's queries before the click. Spar rehearses the target: it mounts the app at that address without drawing anything, which reaches every `ask` on the way, and throws the result away. The queries are real and their answers stay in their stores, so the click finds the data there. Leave `onIntent` off a link whose page should not be preloaded. `router.preload(route, params)` does the same from code. Links you did not write as JSX, such as the ones in trusted markup rendered from markdown, follow in place when their container has `onClick={router.followLinks}`. A plain click on a link to this site goes through the router; a link to another site, one with `target` or `download`, a link to a heading on the same page, and a click with a modifier key are left to the browser. ### Loading a page's code when it is first shown ```tsx const withPage = () => Effect.map( Router.outlet({ routes: [ Router.on(home, EmptyPageView), Router.on(agentRoute, AgentPage), Router.live( orgRoute, View.split(DeepLoadingView, () => import("./DeepPage.tsx").then((module) => module.OrgSegment), ), ), ], otherwise: MissingPageView, }), (page) => ({ page }), ) ``` (`apps/sidebar/src/Shell.tsx`) `View.split` shows the placeholder, a view that takes the same props, until the code has arrived. Routes, param Schemas and query classes stay in the main bundle because the query layers are provided at the root; the components and their views are what is split off. Preloading a link fetches the code too, since the rehearsal mounts the page. On the server and while taking over a server-drawn page the real component is used, not the placeholder. The showcase's deep page is loaded this way, as above. ### Pending and failure, per segment Each segment shows its own query's `status`, so one slow segment does not blank the others. For a component whose own Effect can wait or fail, `View.pending(placeholder)` and `View.recover(failure, view)` wrap that component alone. A query takes `retry`, a schedule, and stays `loading` until the schedule gives up. ### What makes a waterfall, and how Spar stops it One thing: a component whose Effect waits. Everything below it mounts late, so their queries start late. - The build refuses a wait written straight into an enhancer inside `compose(...)`: `yield*` of `Effect.sleep`, `Effect.promise`, `Effect.tryPromise`, `Effect.callback`, `Deferred.await`, `Fiber.join` (rule `no-waiting-in-components`). A wait in a handler, in a service's Effect or anywhere outside a component is fine. - The build cannot see a wait behind a call such as `yield* server.describe(name)`, or in an enhancer written outside the `compose(...)` call. For that, any component that takes a frame or more before its children can mount gets a `waited` entry in the log with its name and the milliseconds, and `spar.waited_ms` on its span. Forbidden, in short: fetching in a component's Effect (ask a query), and passing server data down through props (the component that needs it asks for it, or a store's action reads the query with `TheQuery.read(input)`). ### Seeing it One navigation is one trace, whether it started with a link, `router.go` or the browser's Back and Forward buttons (those run in a span named `Router.popstate`): the click, the route change, each segment mounting, each query's request, the calls they make, the backend's spans, and each answer landing. In the devtools trace panel, lenses show one kind at a time: | Lens | What it keeps | | --------- | -------------------------------------------------------------------------------------- | | Rendering | Components mounting, and each event a component handled (`on click`, with its view) | | Data | Queries: each request, its call, its answer, and what a dependent one's input was from | | Stores | Store commands | | Backend | Spans the backend recorded | A request that waited for another query's value draws that wait as a line before its bar, from when the other was asked for to when this one started. Data that was already there (after a preload, or going back) is a short `/served` span that links to the trace that loaded it. Hovering a link and then clicking it follows one rule. Hovering starts the target page's queries in the hover's own trace. When the click asks for the same queries, nothing is asked again, whether the hover's requests have answered or are still on their way. The click's trace gets a `served` span for each one, saying "served from what trace … loaded" and linking to the hover's trace. So each request is recorded once, in the trace that started it, and the click's trace says where its data came from. When three or more requests each waited for the one before, or when a request had the same input as the one it waited for, the trace panel says so above the spans with the code `SPAR_QUERY_CHAIN`, names the requests in order with how long after the one before each started, and says which one looks avoidable. A chain of two with different inputs, such as a report and then its author, is not reported. An agent gets the same with `get_trace` and a `lens`, or `get_navigation` for the newest route change, which also carries the chains. From a shell: ```sh bun run --cwd packages/devtools-mcp cli trace --lens data ``` prints that navigation as an indented waterfall: each span, when it started, how long it took and what it waited for. `--back 1` is the navigation before; `--id` takes a trace id. ### On the server `Server.render` draws the page, waits until every query has settled, and draws again until a pass finds nothing still loading. That covers queries inside a routed page or a list, which only start once the page is drawn, and dependent ones. The queries' stores travel with the page like any store's, so in the browser the first `ask` finds its data and makes no request. Data the server or a link preload loaded is used once by the first `ask` that wants it, whatever the query's `staleAfter`; asks after that follow `staleAfter`, which is 500 ms unless set (give `"0 millis"` to ask again every time). The server boundary is one Effect RPC group and one service with two layers. On the server the layer reads the database; in the browser it calls the group over `Backend.rpc`. The query's `load` is the same code on both sides. `apps/ssr` shows it with a routed product page: its browser test fails unless the page arrives with what its two queries loaded, the browser asks for none of it again, a link to another product makes exactly two calls in one trace that reaches the database's spans, and going back loads no new document. #### Sending a page in pieces `Server.render` and `renderToStream` wait for every query, so the page arrives complete and works without JavaScript. `Server.renderInPieces` does not wait: ```ts const inPieces = (url: string) => Effect.map( Effect.context(), (context) => new Response( Stream.toReadableStreamWith( Stream.encodeText( Server.renderInPieces(Site, { layer: layer(url, "300 millis"), open, close: "", script: client, end: "", }), ), context, ), { headers: { "content-type": "text/html; charset=utf-8" } }, ), ) ``` (`apps/ssr/scripts/site.ts`) It sends the page as first drawn, with each query showing its own `loading` or `waiting` state, and the state it had then. The queries go on running on the server, dependent ones too, and each time their stores change the new state follows as a small script. The browser hands each piece to the query's store (the store's log shows it as `streamed`), the views update, and the browser asks the backend for nothing. The whole response is one render in one trace. The server code chooses per page which of the two to call. Each data piece is followed by the parts of the page that data changed. The server draws the page again, compares each component with what it last sent, and sends only the components whose own markup changed, each as finished HTML in a `