The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 07:15 UTC
| 1 | # Foldkit frontends |
| 2 | |
| 3 | Foldkit is event-driven like the domain. The app's Commands send domain commands, its Subscriptions turn live view reads into Messages, and `update` folds Messages into the Model. The domain package's Api gives the browser a typed client: no hand-written fetch code, no duplicated schemas. |
| 4 | |
| 5 | ## The Api client as a resource |
| 6 | |
| 7 | Build the client once, for the app's life, and give it to Foldkit as a resource. Sign in first, so the browser carries an `HttpOnly`, `SameSite=Strict` session cookie on the same origin, including on every WebSocket upgrade. |
| 8 | |
| 9 | ```ts |
| 10 | // packages/web/src/entry.ts |
| 11 | import { CustomerApi } from "@acme/domain/CustomerApi.api"; |
| 12 | import * as Domain from "@alchemy.run/domain"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Socket from "effect/socket/Socket"; |
| 17 | import { Runtime } from "foldkit"; |
| 18 | import { Flags, init, Model, subscriptions, update, view } from "./Bank.ts"; |
| 19 | |
| 20 | const BankConnection = Layer.unwrap( |
| 21 | Effect.gen(function* () { |
| 22 | yield* signIn; // POST /api/session |
| 23 | return CustomerApi.layerClient.pipe( |
| 24 | Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)), |
| 25 | Layer.provide(Socket.layerWebSocketConstructorGlobal), |
| 26 | ); |
| 27 | }), |
| 28 | ).pipe(Layer.provide(FetchHttpClient.layer)); |
| 29 | |
| 30 | Runtime.run( |
| 31 | Runtime.makeApplication({ |
| 32 | Model, Flags, init, update, view, subscriptions, |
| 33 | resources: BankConnection, |
| 34 | container: document.getElementById("root"), |
| 35 | }), |
| 36 | { flags: Effect.succeed({ /* ... */ }) }, |
| 37 | ); |
| 38 | ``` |
| 39 | |
| 40 | More: [Integrate with Foldkit: Provide the client and headers](https://alchemy.run/domain/foldkit#provide-the-client-and-headers). |
| 41 | |
| 42 | ## Derive the Commands |
| 43 | |
| 44 | Use the optional `@alchemy.run/domain/Foldkit` subpath with Foldkit 0.169 or later. |
| 45 | |
| 46 | ```ts |
| 47 | import * as DomainFoldkit from "@alchemy.run/domain/Foldkit"; |
| 48 | import { Command, Subscription } from "foldkit"; |
| 49 | import * as Option from "effect/Option"; |
| 50 | |
| 51 | const BankClient = DomainFoldkit.make(CustomerApi); |
| 52 | |
| 53 | const send = BankClient.DepositMoney({ |
| 54 | target: model.accountId, |
| 55 | input: { amount: 1_000 }, |
| 56 | commandId: allocation.commandId, |
| 57 | }); |
| 58 | const command = Command.mapMessage(send, (result) => Message.ReceivedBankResult({ result })); |
| 59 | ``` |
| 60 | |
| 61 | Allocate ids with `DomainFoldkit.next(model.commandIds)` and store the returned state with `modifyFields`. Declare `ReceivedBankResult` with `{ result: BankClient.Message }`. Match the result through `BankClient.Message.match`: `SucceededDepositMoney` carries the reply and receipt; `FailedDepositMoney` carries `Rejected`, `Denied`, or `Unknown`. Preserve Rejection and middleware error fields. Retry `Unknown` with the original id because the write may have committed. Command defects also produce `Unknown`. |
| 62 | |
| 63 | More: [Integrate with Foldkit: Derive the Commands](https://alchemy.run/domain/foldkit#derive-the-commands), [Send a command from update](https://alchemy.run/domain/foldkit#send-a-command-from-update). |
| 64 | |
| 65 | ## Follow a View's state |
| 66 | |
| 67 | ```ts |
| 68 | const subscriptions = Subscription.make<Model, Message, Bank>()(() => ({ |
| 69 | summary: BankClient.AccountSummary.watch({ |
| 70 | key: (model: Model) => model.accountId, |
| 71 | isEnabled: (model) => model.online, |
| 72 | toMessage: ({ state, cursor }): Message => Message.ReceivedBalance({ |
| 73 | balance: Option.map(state, (summary) => summary.balance), |
| 74 | cursor, |
| 75 | }), |
| 76 | onFailure: (error): Message => Message.FailedWatchSummary({ reason: error._tag }), |
| 77 | onDefect: (): Message => Message.FailedWatchSummary({ reason: "Read defect" }), |
| 78 | }), |
| 79 | statement: BankClient.Statement.events({ |
| 80 | key: (model: Model) => model.accountId, |
| 81 | cursor: (model) => model.statementCursor, |
| 82 | isEnabled: (model) => model.online, |
| 83 | onEntry: ({ event, envelope }): Message => Message.ReceivedLine({ |
| 84 | commandId: envelope.commandId, |
| 85 | line: event, |
| 86 | cursor: envelope.seq, |
| 87 | }), |
| 88 | onCaughtUp: (cursor): Message => Message.CaughtUpStatement({ cursor }), |
| 89 | onFailure: (error): Message => Message.FailedReadStatement({ reason: error._tag }), |
| 90 | onDefect: (): Message => Message.FailedReadStatement({ reason: "Read defect" }), |
| 91 | }), |
| 92 | })); |
| 93 | ``` |
| 94 | |
| 95 | Store absent state and the event cursor with `Option`. Apply each line and its cursor in one update. Cursor changes do not restart the feed. `onFailure` handles typed read failures; `onDefect` receives unexpected read Causes. Interruption ends the read without a Message. Mark the feed live after `CaughtUpStatement`. |
| 96 | |
| 97 | Decode snapshot Flags with `BankClient.AccountSummary.decodeSnapshotFlags`. Use `watch` for current state and `events` for output entries and command confirmation. |
| 98 | |
| 99 | More: [Integrate with Foldkit: Follow a View's state](https://alchemy.run/domain/foldkit#follow-a-views-state), [Seed the first paint](https://alchemy.run/domain/foldkit#seed-the-first-paint), [Optimistic updates: Resume the feed](https://alchemy.run/domain/optimistic-updates#resume-the-feed). |
| 100 | |
| 101 | ## Tracing from the browser |
| 102 | |
| 103 | Foldkit wraps every Command in a span, and Api calls carry the trace to the server (live reads too). Put a tracer in `resources` that exports to the app's own origin, and collect it in the server Worker with `Telemetry.relay`, which forwards it with the server's credentials: |
| 104 | |
| 105 | ```ts |
| 106 | // packages/web/src/entry.ts |
| 107 | const Tracing = OtlpTracer.layer({ |
| 108 | url: `${location.origin}/api/telemetry/v1/traces`, |
| 109 | resource: { serviceName: "bank-web" }, |
| 110 | }).pipe(Layer.provide(OtlpSerialization.layerJson)); |
| 111 | const Resources = Layer.mergeAll(BankConnection, Tracing).pipe(Layer.provide(FetchHttpClient.layer)); |
| 112 | |
| 113 | // packages/server/src/BankWorker.ts |
| 114 | import * as Telemetry from "alchemy/Telemetry"; |
| 115 | const telemetry = Telemetry.relay({ |
| 116 | authorize: Effect.map(HttpServerRequest, (r) => Option.isSome(actorOf(r.headers))), // signed-in only |
| 117 | // route: (signal, configured) => Effect.succeed(configured), // choose destinations |
| 118 | }); |
| 119 | if (path.startsWith("/api/telemetry/")) return yield* telemetry; |
| 120 | ``` |
| 121 | |
| 122 | Never put an ingest token in the browser. Workers Observability can't receive browser spans, so relay them to an OTLP destination (Axiom, a collector). |
| 123 | |
| 124 | More: [Observability: Trace the browser](https://alchemy.run/domain/observability#trace-the-browser). |
| 125 | |
| 126 | ## Optimistic updates and offline |
| 127 | |
| 128 | - **Optimistic UI.** Send each command with a `commandId` the app chooses, and show it as pending. The view event carrying that `commandId` confirms it, and a typed rejection marks it rejected. Show the server's balance plus every unacknowledged line, so nothing is ever rolled back. |
| 129 | - **Offline intents.** Record what the user asked for, never facts the server owns. Queue unreachable sends in order and persist them to `localStorage`. Deliver them when back online, deduplicated by `commandId`. A conflict is just a typed rejection. |
| 130 | |
| 131 | - **Predicted outcome.** `MyAggregate.predict(state, command, { id, now, context })` runs the aggregate's own `decide` and `evolve`: `Accepted` (events, envelopes, next state), `Rejected` (the same rejection the server returns), or `Unpredictable` (only the server can tell: `decide` suspended, died, or broke its declaration). `MyView.evolve(state, { name, event, source, envelope })` folds a predicted event like the server's view. `context` is required, by type, for whatever the command's middleware provides: build it from a client-side Layer of the same services (`yield* Layer.build(ClientSession)`). Still confirm from the stream. |
| 132 | |
| 133 | A local mirror of server aggregates, or local-authority sync, isn't supported. It needs a sync engine or CRDTs. |
| 134 | |
| 135 | More: [Optimistic updates](https://alchemy.run/domain/optimistic-updates), [Offline and local first](https://alchemy.run/domain/local-first). |
| 136 | |
| 137 | ## Hosting the app |
| 138 | |
| 139 | `Cloudflare.Website.Foldkit` builds the app with Vite and serves it from its own Worker. That Worker forwards `/api` to the server over a service binding, so the app and the Api share one origin: |
| 140 | |
| 141 | ```ts |
| 142 | // packages/web/src/worker.ts |
| 143 | export default { |
| 144 | fetch(request: Request, env: { readonly ASSETS: Fetcher; readonly BANK: Fetcher }) { |
| 145 | return new URL(request.url).pathname.startsWith("/api") ? env.BANK.fetch(request) : env.ASSETS.fetch(request); |
| 146 | }, |
| 147 | }; |
| 148 | ``` |
| 149 | |
| 150 | More: [Integrate with Foldkit: Test and host the app](https://alchemy.run/domain/foldkit#test-and-host-the-app). |
| 151 | |
| 152 | ## Testing the app |
| 153 | |
| 154 | Test `update` and the Commands with Foldkit stories (`foldkit/story`) in `packages/web/test`. They need no server. |
| 155 | |
| 156 | More: [Integrate with Foldkit: Test and host the app](https://alchemy.run/domain/foldkit#test-and-host-the-app). |