The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 658 lines 25.1 KB
Raw
1 ---
2 title: Offline and local first
3 description: Choose how local an app is, and keep it working offline by recording intents and sending them when the connection returns.
4 ---
5
6 How local an app can be depends on who decides what the user does: the server, or the device. There are four ways to build it. Two of them work with a domain model today.
7
8 ## Optimistic updates
9
10 The server decides. The app shows a change before the server confirms it, and confirms or rejects it when the answer arrives. See [Optimistic updates](/domain/optimistic-updates).
11
12 ## Offline intents
13
14 The server still decides, but the app keeps working without a connection. It records what the user asked for, an intent, and never a fact only the server can establish. Intents wait in a queue, survive a reload, and go to the server in order once it can be reached. A conflict is just a rejection: a withdrawal made offline against money that's gone comes back `InsufficientFunds`. The rest of this page builds this.
15
16 ## A local copy of the server's aggregates
17
18 Here the device runs its own copy of an account and records facts in it offline, and everything the user does next builds on them. When the server later rejects one, everything built on it is wrong. Making that safe takes a sync engine that keeps the server's state apart from pending changes and recomputes everything whenever the server's state moves. `@alchemy.run/domain` doesn't include one.
19
20 ## The device decides, the server stores
21
22 Here every device accepts changes and the server only keeps a copy. Nothing can refuse a change, so conflicts must be merged, with CRDTs, last-writer-wins, or rules specific to your data. A domain model assumes one place decides each aggregate, so this calls for a different tool.
23
24 ## Record intents
25
26 The app below extends optimistic updates with a queue. Each line the server hasn't acknowledged is an intent, saved to `localStorage` under the customer's key.
27
28 ```typescript
29 // packages/web/src/Bank.ts
30 import { AccountId, mainAccountId } from "@bank/domain/Account/Account.id";
31 import { StatementLine } from "@bank/domain/Account/Statement.view";
32 import { CustomerId } from "@bank/domain/Customer/Customer.id";
33 import { Username } from "@bank/domain/Customer/Username";
34 import { CustomerApi } from "@bank/domain/CustomerApi.api";
35 import * as Domain from "@alchemy.run/domain";
36 import * as Effect from "effect/Effect";
37 import * as Schedule from "effect/Schedule";
38 import * as Schema from "effect/Schema";
39 import * as Stream from "effect/Stream";
40 import { Command, Subscription, type Update } from "foldkit";
41 import type { Document, HtmlBuilder } from "foldkit/html";
42 import { defineMessageUnion } from "foldkit/message";
43
44 /** The bank client this app runs on, provided by the `resources` Layer in `entry.ts`. */
45 type Bank = Domain.Api.ClientKey<"CustomerApi">;
46
47 /** The demo MFA code `MfaChallenge` accepts. */
48 const mfa = { headers: { "x-mfa-code": "000000" } };
49
50 // INTENTS: what the customer asked for that the server has not acknowledged.
51 // They are kept across reloads, so asking works offline.
52
53 /** A deposit or withdrawal the customer asked for, named by the command that carries it. */
54 export const Intent = Schema.Struct({
55 commandId: Schema.String,
56 kind: Schema.Literals(["deposit", "withdrawal"]),
57 amount: Schema.Number,
58 });
59 export type Intent = typeof Intent.Type;
60
61 /** Where a customer's unacknowledged intents are kept between page loads. */
62 export const intentsKey = (customerId: CustomerId) => `bank:intents:${customerId}`;
63
64 // FLAGS: who is signed in, and what this browser still owes the server.
65
66 export const Flags = Schema.Struct({
67 customerId: CustomerId,
68 /** Unique per page load; with a counter, it names every command this page sends. */
69 session: Schema.String,
70 online: Schema.Boolean,
71 /** Intents saved by an earlier page load, oldest first. */
72 intents: Schema.Array(Intent),
73 });
74 export type Flags = typeof Flags.Type;
75
76 // MODEL
77
78 /**
79 * Whether the server has acknowledged a line:
80 * - `pending`: sent, waiting for the event it causes on the statement stream;
81 * - `queued`: not sent, because the server could not be reached; sent when back online;
82 * - `confirmed`: its event arrived;
83 * - `rejected`: the account refused the command.
84 */
85 export const Ack = Schema.Literals(["pending", "queued", "confirmed", "rejected"]);
86 export type Ack = typeof Ack.Type;
87
88 /** A statement line, shown before the server has acknowledged it. */
89 export const Line = Schema.Struct({
90 /** The command that made it. An optimistic line and the event that confirms it share it. */
91 commandId: Schema.String,
92 kind: StatementLine.fields.kind,
93 amount: Schema.Number,
94 /** The balance after this line; known once it is confirmed. */
95 balance: Schema.NullOr(Schema.Number),
96 ack: Ack,
97 /** Why the account refused it. */
98 reason: Schema.NullOr(Schema.String),
99 });
100 export type Line = typeof Line.Type;
101
102 export const Model = Schema.Struct({
103 customerId: CustomerId,
104 accountId: AccountId,
105 session: Schema.String,
106 /** Commands this page has sent: with `session`, the next command's id. */
107 sent: Schema.Number,
108 online: Schema.Boolean,
109 /** `null` until the main account exists (register to open it). */
110 balance: Schema.NullOr(Schema.Number),
111 /** Unacknowledged lines first, then confirmed ones, newest first. */
112 lines: Schema.Array(Line),
113 error: Schema.NullOr(Schema.String),
114 });
115 export type Model = typeof Model.Type;
116
117 /** What delivering one intent came to. */
118 export const Outcome = Schema.Struct({
119 commandId: Schema.String,
120 /** `accepted` waits for its event; `queued` waits for the network. */
121 result: Schema.Literals(["accepted", "queued", "rejected"]),
122 reason: Schema.NullOr(Schema.String),
123 });
124 export type Outcome = typeof Outcome.Type;
125
126 // MESSAGE
127
128 export const Message = defineMessageUnion({
129 ClickedRegister: {},
130 ClickedDeposit: {},
131 ClickedWithdraw: {},
132 SucceededCommand: {},
133 FailedCommand: { reason: Schema.String },
134 /** Intents were delivered in order, up to the first that could not reach the server. */
135 Delivered: { outcomes: Schema.Array(Outcome) },
136 SavedIntents: {},
137 WentOnline: {},
138 WentOffline: {},
139 GotBalance: { balance: Schema.NullOr(Schema.Number) },
140 /** A statement event, and the command that caused it. */
141 GotLine: { commandId: Schema.String, line: StatementLine },
142 FailedWatch: { reason: Schema.String },
143 });
144 export type Message = typeof Message.Type;
145
146 // COMMANDS: each runs domain commands over the app's connection.
147
148 /** Register the signed-in customer; a policy then opens their main account. */
149 export const Register = Command.define("Register", {
150 args: { customerId: CustomerId },
151 messages: [Message.SucceededCommand, Message.FailedCommand],
152 execute: ({ customerId }) =>
153 Effect.gen(function* () {
154 const bank = yield* CustomerApi.Client;
155 yield* bank.RegisterCustomer(customerId, { name: customerId, username: Username.make(customerId) });
156 return Message.SucceededCommand();
157 }).pipe(Effect.catch((error) => Effect.succeed(Message.FailedCommand({ reason: error._tag })))),
158 });
159
160 /**
161 * Send one intent. A dropped connection is retried briefly, which is safe
162 * because the account deduplicates by `commandId`: a send that did land is
163 * not applied twice. If the server still cannot be reached, the intent is
164 * queued; a rejection is the account's answer.
165 */
166 const deliver = (accountId: AccountId, intent: Intent) =>
167 Effect.gen(function* () {
168 const bank = yield* CustomerApi.Client;
169 const { commandId, amount } = intent;
170 const send =
171 intent.kind === "deposit"
172 ? bank.DepositMoney(accountId, { amount }, { commandId })
173 : bank.WithdrawMoney(accountId, { amount }, { commandId, ...mfa });
174 return yield* send.pipe(
175 Effect.retry({
176 while: (error) => error._tag === "RpcClientError",
177 schedule: Schedule.exponential("200 millis"),
178 times: 3,
179 }),
180 Effect.as<Outcome>({ commandId, result: "accepted", reason: null }),
181 Effect.catch((error) =>
182 Effect.succeed<Outcome>(
183 error._tag === "RpcClientError"
184 ? { commandId, result: "queued", reason: null }
185 : { commandId, result: "rejected", reason: error._tag },
186 ),
187 ),
188 );
189 });
190
191 /**
192 * Deliver intents in the order they were made, stopping at the first that
193 * cannot reach the server: the rest stay queued, so a withdrawal never
194 * overtakes the deposit it was made after.
195 */
196 export const Deliver = Command.define("Deliver", {
197 args: { accountId: AccountId, intents: Schema.Array(Intent) },
198 messages: [Message.Delivered],
199 execute: ({ accountId, intents }) =>
200 Effect.gen(function* () {
201 const outcomes: Array<Outcome> = [];
202 for (const intent of intents) {
203 const outcome = yield* deliver(accountId, intent);
204 outcomes.push(outcome);
205 if (outcome.result === "queued") {
206 for (const rest of intents.slice(outcomes.length)) {
207 outcomes.push({ commandId: rest.commandId, result: "queued", reason: null });
208 }
209 break;
210 }
211 }
212 return Message.Delivered({ outcomes });
213 }),
214 });
215
216 /** Keep the unacknowledged intents for the next page load. */
217 export const SaveIntents = Command.define("SaveIntents", {
218 args: { customerId: CustomerId, intents: Schema.Array(Intent) },
219 messages: [Message.SavedIntents],
220 execute: ({ customerId, intents }) =>
221 Effect.sync(() => {
222 localStorage.setItem(intentsKey(customerId), JSON.stringify(intents));
223 return Message.SavedIntents();
224 }),
225 });
226
227 // UPDATE
228
229 /** The next command's id. Unique across page loads, and stable if the command is resent. */
230 const nextCommandId = (model: Model) => `${model.session}:${model.sent}`;
231
232 const isIntent = (line: Line): line is Line & { readonly kind: Intent["kind"] } =>
233 (line.ack === "pending" || line.ack === "queued") &&
234 (line.kind === "deposit" || line.kind === "withdrawal");
235
236 /** The model's unacknowledged intents, oldest first. */
237 const intentsOf = (model: Model): Array<Intent> =>
238 model.lines
239 .filter(isIntent)
240 .map(({ commandId, kind, amount }) => ({ commandId, kind, amount }))
241 .reverse();
242
243 const save = (model: Model) =>
244 SaveIntents({ customerId: model.customerId, intents: intentsOf(model) });
245
246 /**
247 * Add a line the server has not acknowledged, above every other line. Sent
248 * now if the server is reachable and nothing older is waiting; otherwise
249 * queued behind what is.
250 */
251 const ask = (
252 model: Model,
253 kind: Intent["kind"],
254 amount: number,
255 ): Update.Return<Model, Message, Bank> => {
256 const commandId = nextCommandId(model);
257 const send = model.online && !model.lines.some((l) => l.ack === "queued");
258 const next: Model = {
259 ...model,
260 sent: model.sent + 1,
261 error: null,
262 lines: [
263 { commandId, kind, amount, balance: null, ack: send ? "pending" : "queued", reason: null },
264 ...model.lines,
265 ],
266 };
267 return {
268 model: next,
269 commands: [
270 save(next),
271 ...(send
272 ? [Deliver({ accountId: model.accountId, intents: [{ commandId, kind, amount }] })]
273 : []),
274 ],
275 };
276 };
277
278 /** Send every queued intent, oldest first. */
279 const flush = (model: Model): Update.Return<Model, Message, Bank> => {
280 const queued = intentsOf(model).filter((intent) =>
281 model.lines.some((l) => l.commandId === intent.commandId && l.ack === "queued"),
282 );
283 if (queued.length === 0) return { model };
284 const sending = new Set(queued.map((intent) => intent.commandId));
285 return {
286 model: {
287 ...model,
288 lines: model.lines.map((l) => (sending.has(l.commandId) ? { ...l, ack: "pending" } : l)),
289 },
290 commands: [Deliver({ accountId: model.accountId, intents: queued })],
291 };
292 };
293
294 /**
295 * Apply what delivery came to. A confirmed line stays confirmed: its event
296 * can arrive before the reply.
297 */
298 const delivered = (model: Model, outcomes: ReadonlyArray<Outcome>): Model => {
299 const byId = new Map(outcomes.map((o) => [o.commandId, o]));
300 return {
301 ...model,
302 lines: model.lines.map((l): Line => {
303 const outcome = byId.get(l.commandId);
304 if (!outcome || l.ack === "confirmed") return l;
305 switch (outcome.result) {
306 case "accepted":
307 return l;
308 case "queued":
309 return { ...l, ack: "queued" };
310 case "rejected":
311 return { ...l, ack: "rejected", reason: outcome.reason };
312 }
313 }),
314 };
315 };
316
317 /**
318 * A statement event arrived. If this browser asked for it, its line becomes
319 * confirmed; otherwise (history, a transfer, another device) it is a new
320 * line. Either way it goes above the confirmed lines and below the
321 * unacknowledged ones.
322 */
323 const confirm = (model: Model, commandId: string, line: StatementLine): Model => {
324 const confirmed: Line = {
325 commandId,
326 kind: line.kind,
327 amount: line.amount,
328 balance: line.balance,
329 ack: "confirmed",
330 reason: null,
331 };
332 const others = model.lines.filter((l) => l.commandId !== commandId);
333 const unacknowledged = others.filter((l) => l.ack !== "confirmed");
334 const acknowledged = others.filter((l) => l.ack === "confirmed");
335 return { ...model, lines: [...unacknowledged, confirmed, ...acknowledged] };
336 };
337
338 export const update = (model: Model, message: Message): Update.Return<Model, Message, Bank> =>
339 Message.match<Update.Return<Model, Message, Bank>>(message, {
340 ClickedRegister: () => ({ model, commands: [Register({ customerId: model.customerId })] }),
341 ClickedDeposit: () => ask(model, "deposit", 1_000),
342 ClickedWithdraw: () => ask(model, "withdrawal", 1_000),
343 SucceededCommand: () => ({ model: { ...model, error: null } }),
344 FailedCommand: ({ reason }) => ({ model: { ...model, error: reason } }),
345 Delivered: ({ outcomes }) => {
346 const next = delivered(model, outcomes);
347 return { model: next, commands: [save(next)] };
348 },
349 SavedIntents: () => ({ model }),
350 WentOnline: () => flush({ ...model, online: true }),
351 WentOffline: () => ({ model: { ...model, online: false } }),
352 GotBalance: ({ balance }) => ({ model: { ...model, balance } }),
353 GotLine: ({ commandId, line }) => {
354 const next = confirm(model, commandId, line);
355 return { model: next, commands: [save(next)] };
356 },
357 FailedWatch: ({ reason }) => ({ model: { ...model, error: `watch ended: ${reason}` } }),
358 });
359
360 // INIT: the signed-in customer's main account, and what an earlier page load still owes.
361
362 export const init = (flags: Flags): Update.Return<Model, Message, Bank> => {
363 const model: Model = {
364 customerId: flags.customerId,
365 accountId: mainAccountId(flags.customerId),
366 session: flags.session,
367 sent: 0,
368 online: flags.online,
369 balance: null,
370 // Restored intents are queued: the statement's history confirms those the
371 // server already applied, and the rest are sent when online.
372 lines: flags.intents
373 .map((intent): Line => ({ ...intent, balance: null, ack: "queued", reason: null }))
374 .reverse(),
375 error: null,
376 };
377 return model.online ? flush(model) : { model };
378 };
379
380 // SUBSCRIPTIONS: connectivity, and the account's summary (snapshots) and
381 // statement (events), live while online.
382
383 export const subscriptions = Subscription.make<Model, Message, Bank>()((entry) => ({
384 connectivity: entry(
385 {},
386 {
387 modelToDependencies: () => ({}),
388 dependenciesToStream: () =>
389 Stream.merge(
390 Stream.fromEventListener(window, "online").pipe(Stream.as(Message.WentOnline())),
391 Stream.fromEventListener(window, "offline").pipe(Stream.as(Message.WentOffline())),
392 ),
393 },
394 ),
395 // Depending on `online` restarts a watch when the browser comes back,
396 // however long it was gone.
397 summary: entry(
398 { accountId: AccountId, online: Schema.Boolean },
399 {
400 modelToDependencies: (model) => ({ accountId: model.accountId, online: model.online }),
401 dependenciesToStream: ({ accountId, online }) =>
402 online
403 ? Stream.unwrap(
404 Effect.gen(function* () {
405 const bank = yield* CustomerApi.Client;
406 return bank.AccountSummary.watch(accountId);
407 }),
408 ).pipe(
409 Stream.map(({ state }) => Message.GotBalance({ balance: state?.balance ?? null })),
410 Stream.catch((error) => Stream.succeed(Message.FailedWatch({ reason: error._tag }))),
411 )
412 : Stream.empty,
413 },
414 ),
415 statement: entry(
416 { accountId: AccountId, online: Schema.Boolean },
417 {
418 modelToDependencies: (model) => ({ accountId: model.accountId, online: model.online }),
419 dependenciesToStream: ({ accountId, online }) =>
420 online
421 ? Stream.unwrap(
422 Effect.gen(function* () {
423 const bank = yield* CustomerApi.Client;
424 return bank.Statement.events(accountId);
425 }),
426 ).pipe(
427 Stream.filter(Domain.Read.isEvent),
428 Stream.map(({ event, envelope }) =>
429 Message.GotLine({ commandId: envelope.commandId, line: event }),
430 ),
431 Stream.catch((error) => Stream.succeed(Message.FailedWatch({ reason: error._tag }))),
432 )
433 : Stream.empty,
434 },
435 ),
436 }));
437
438 // VIEW
439
440 /** How an unacknowledged line will move the balance once it is confirmed. */
441 const signed = (line: Line) =>
442 line.kind === "deposit" ||
443 line.kind === "transfer-in" ||
444 line.kind === "refund" ||
445 line.kind === "settlement"
446 ? line.amount
447 : -line.amount;
448
449 /**
450 * The balance to show: the newest confirmed balance (the statement's, so it
451 * moves with the lines it confirms), plus every unacknowledged line. Nothing
452 * here is committed, so a line the account later rejects simply stops
453 * counting.
454 */
455 export const shownBalance = (model: Model): number | null => {
456 if (model.balance === null) return null;
457 const confirmed = model.lines.find((l) => l.ack === "confirmed")?.balance ?? model.balance;
458 return model.lines
459 .filter((l) => l.ack === "pending" || l.ack === "queued")
460 .reduce((sum, l) => sum + signed(l), confirmed);
461 };
462
463 const button = "bg-black text-white hover:bg-gray-700 px-4 py-2";
464
465 const cents = (amount: number) => (amount / 100).toFixed(2);
466
467 const lineView = (line: Line, h: HtmlBuilder<Message>) => {
468 const text = `${line.kind} ${cents(line.amount)}`;
469 switch (line.ack) {
470 case "pending":
471 return h.li([h.Class("text-gray-400 italic")], [`${text}, sending`]);
472 case "queued":
473 return h.li([h.Class("text-amber-600 italic")], [`${text}, queued until online`]);
474 case "rejected":
475 return h.li([h.Class("text-red-600 line-through")], [`${text}, rejected: ${line.reason}`]);
476 case "confirmed":
477 return h.li([], [`${text}, balance ${cents(line.balance ?? 0)}`]);
478 }
479 };
480
481 export const view = (model: Model, h: HtmlBuilder<Message>): Document => {
482 const balance = shownBalance(model);
483 const unacknowledged = model.lines.some((l) => l.ack === "pending" || l.ack === "queued");
484 return {
485 title: balance === null ? "Bank" : `Balance: ${cents(balance)}`,
486 body: h.div(
487 [h.Class("flex flex-col gap-4 p-8")],
488 [
489 h.p([], [`Signed in as ${model.customerId}`]),
490 ...(model.online
491 ? []
492 : [
493 h.p(
494 [h.Class("text-amber-600")],
495 ["Offline: changes are kept and sent when you reconnect."],
496 ),
497 ]),
498 ...(balance === null
499 ? [h.button([h.OnClick(Message.ClickedRegister()), h.Class(button)], ["Open my account"])]
500 : [
501 h.div(
502 [
503 h.Class(
504 unacknowledged ? "text-4xl font-bold text-gray-400" : "text-4xl font-bold",
505 ),
506 ],
507 [unacknowledged ? `${cents(balance)} (pending)` : cents(balance)],
508 ),
509 h.div(
510 [h.Class("flex gap-2")],
511 [
512 h.button(
513 [h.OnClick(Message.ClickedDeposit()), h.Class(button)],
514 ["Deposit 10.00"],
515 ),
516 h.button(
517 [h.OnClick(Message.ClickedWithdraw()), h.Class(button)],
518 ["Withdraw 10.00"],
519 ),
520 ],
521 ),
522 ]),
523 h.p([h.Class("text-red-600")], [model.error ?? ""]),
524 h.ul(
525 [],
526 model.lines.map((line) => lineView(line, h)),
527 ),
528 ],
529 ),
530 };
531 };
532 ```
533
534 ## Queue what can't be sent
535
536 `ask` sends an intent only when the browser is online and nothing older is waiting. Otherwise the line is `queued`, behind the others, so a withdrawal never overtakes the deposit made before it.
537
538 `Deliver` sends intents in order and stops at the first one that can't reach the server: that one and everything after it stay queued. A typed rejection marks just that line `rejected`.
539
540 ## Send the queue when the connection returns
541
542 The `connectivity` subscription turns the browser's `online` and `offline` events into messages. `WentOnline` calls `flush`, which sends every queued intent, oldest first. The summary and statement subscriptions depend on `online`, so they restart when the connection returns, however long it was gone.
543
544 ## Keep intents across reloads
545
546 Every change to the intents saves them with `SaveIntents`. On the next page load, the entry point reads them back into `Flags`.
547
548 ```typescript
549 // packages/web/src/entry.ts
550 import { CustomerId } from "@bank/domain/Customer/Customer.id";
551 import { CustomerApi } from "@bank/domain/CustomerApi.api";
552 import * as Domain from "@alchemy.run/domain";
553 import * as Effect from "effect/Effect";
554 import * as FetchHttpClient from "effect/http/FetchHttpClient";
555 import * as HttpClient from "effect/http/HttpClient";
556 import * as HttpClientRequest from "effect/http/HttpClientRequest";
557 import * as Layer from "effect/Layer";
558 import * as OtlpSerialization from "effect/observability/OtlpSerialization";
559 import * as OtlpTracer from "effect/observability/OtlpTracer";
560 import * as Option from "effect/Option";
561 import * as Schema from "effect/Schema";
562 import * as Socket from "effect/socket/Socket";
563 import { Runtime } from "foldkit";
564 import { Flags, Intent, init, intentsKey, Model, subscriptions, update, view } from "./Bank.ts";
565
566 /**
567 * The signed-in customer. A demo stand-in for a login: `?customer=c-2` picks
568 * who you are, defaulting to `c-1`.
569 */
570 const signedIn = Effect.sync(() =>
571 CustomerId.make(new URLSearchParams(location.search).get("customer") ?? "c-1"),
572 );
573
574 /** Intents an earlier page load could not deliver. Anything unreadable is dropped. */
575 const savedIntents = (customerId: CustomerId) =>
576 Effect.sync(() =>
577 Option.getOrElse(
578 Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Array(Intent)))(
579 localStorage.getItem(intentsKey(customerId)) ?? "[]",
580 ),
581 () => [],
582 ),
583 );
584
585 /** Sign in: the Api sets an `HttpOnly` session cookie on this origin. */
586 const signIn = Effect.fn(function* (customerId: CustomerId) {
587 const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient);
588 yield* client.execute(
589 HttpClientRequest.post("/api/session").pipe(HttpClientRequest.bodyJsonUnsafe({ customerId })),
590 );
591 });
592
593 /**
594 * The bank Api for the life of the app, on this origin, so the browser sends
595 * the session cookie with every call and every watch. Commands go over HTTP;
596 * each watch is a WebSocket to the Durable Object that owns what it reads,
597 * which pushes every change.
598 */
599 const BankConnection = Layer.unwrap(
600 Effect.gen(function* () {
601 // The app cannot run signed out.
602 yield* signIn(yield* signedIn).pipe(Effect.orDie);
603 return CustomerApi.layerClient.pipe(
604 Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)),
605 Layer.provide(Socket.layerWebSocketConstructorGlobal),
606 );
607 }),
608 );
609
610 /**
611 * The app's spans, exported to its own origin, where the bank Worker relays
612 * them on. foldkit traces every Command, and each Api call carries the trace
613 * on, so a click and everything it causes on the server is one trace.
614 */
615 const Tracing = OtlpTracer.layer({
616 url: `${location.origin}/api/telemetry/v1/traces`,
617 resource: { serviceName: "bank-web" },
618 }).pipe(Layer.provide(OtlpSerialization.layerJson));
619
620 const Resources = Layer.mergeAll(BankConnection, Tracing).pipe(
621 Layer.provide(FetchHttpClient.layer),
622 );
623
624 Runtime.run(
625 Runtime.makeApplication({
626 Model,
627 Flags,
628 init,
629 update,
630 view,
631 subscriptions,
632 resources: Resources,
633 container: document.getElementById("root"),
634 }),
635 {
636 flags: Effect.gen(function* () {
637 const customerId = yield* signedIn;
638 return {
639 customerId,
640 // Names this page's commands, so each is unique even across reloads.
641 session: crypto.randomUUID(),
642 online: navigator.onLine,
643 intents: yield* savedIntents(customerId),
644 };
645 }),
646 },
647 );
648 ```
649
650 `init` restores them as `queued` and flushes them. The statement replays its history first, and confirms any intent the server already applied. The rest are sent again, and the account recognizes any it already applied by their command id, so none happens twice.
651
652 ## Test it
653
654 The example's foldkit stories queue intents offline, send them in order once online, restore them on boot, and show a refused withdrawal no longer counting: see [`packages/web/test/Bank.test.ts`](https://github.com/alchemy-run/alchemy/blob/main/examples/cloudflare-domain/packages/web/test/Bank.test.ts).
655
656 :::note
657 Start from [Optimistic updates](/domain/optimistic-updates) if you only need the app to feel instant online.
658 :::