The best way to control Claude Code, Codex and more from any computer or phone
| 1 | --- |
| 2 | title: Integrate with Foldkit |
| 3 | description: Derive Foldkit Commands from an Api, follow View snapshots, and seed the Model from Flags. |
| 4 | --- |
| 5 | |
| 6 | [Foldkit](https://foldkit.dev) changes its Model through Messages. Commands perform side effects. Subscriptions follow live data. The optional `@alchemy.run/domain/Foldkit` adapter connects these parts to a Domain Api. |
| 7 | |
| 8 | Install `foldkit` in the web package. Domain's root entry does not import it. The adapter targets the workspace's Foldkit `^0.169.0`. |
| 9 | |
| 10 | ## Derive the Commands |
| 11 | |
| 12 | ```typescript |
| 13 | import * as DomainFoldkit from "@alchemy.run/domain/Foldkit"; |
| 14 | import { CustomerApi } from "@bank/domain/CustomerApi.api"; |
| 15 | |
| 16 | export const Bank = DomainFoldkit.make(CustomerApi); |
| 17 | ``` |
| 18 | |
| 19 | `Bank` has one Command per Api command and a read namespace for each View, Aggregate, and Stream. Each read namespace has `watch` and `events`. View namespaces also have `SnapshotFlags` and `decodeSnapshotFlags`. The name `Message` is reserved: `make` does not compile for an Api with an entry named `Message`. Each Command takes `{ target, input, commandId }`. Its result is `Bank.Message.Succeeded<Name>` or `Bank.Message.Failed<Name>`. |
| 20 | |
| 21 | A success carries `reply` and `receipt: { stream, version }`. Pass the receipt to a read's `atLeast` option when that read must include the write. |
| 22 | |
| 23 | ## Name each send |
| 24 | |
| 25 | ```typescript |
| 26 | import * as Schema from "effect/Schema"; |
| 27 | |
| 28 | export const Flags = Schema.Struct({ |
| 29 | session: Schema.String, |
| 30 | summary: Schema.Unknown, |
| 31 | }); |
| 32 | |
| 33 | export const Model = Schema.Struct({ |
| 34 | accountId: AccountId, |
| 35 | commandIds: DomainFoldkit.CommandIds, |
| 36 | summary: Schema.Option((AccountSummary.definition.state ?? Schema.Never)), |
| 37 | summaryCursor: Schema.Option(Schema.Number), |
| 38 | }); |
| 39 | export type Model = typeof Model.Type; |
| 40 | ``` |
| 41 | |
| 42 | `AccountId` and `AccountSummary` come from the bank domain. The server or browser supplies a fresh `session` for each page load. Do not reuse a session from cached HTML. |
| 43 | |
| 44 | ## Send a command from update |
| 45 | |
| 46 | ```typescript |
| 47 | import { Command, type Update } from "foldkit"; |
| 48 | import { defineMessageUnion } from "foldkit/message"; |
| 49 | import { modifyFields } from "foldkit/struct"; |
| 50 | |
| 51 | export const Message = defineMessageUnion({ |
| 52 | ClickedDeposit: {}, |
| 53 | ReceivedBankResult: { result: Bank.Message }, |
| 54 | }); |
| 55 | export type Message = typeof Message.Type; |
| 56 | |
| 57 | const deposit = (model: Model): Update.Return<Model, Message, typeof CustomerApi.Client.Identifier> => { |
| 58 | const allocation = DomainFoldkit.next(model.commandIds); |
| 59 | return { |
| 60 | model: modifyFields(model, { commandIds: () => allocation.commandIds }), |
| 61 | commands: [Command.mapMessage( |
| 62 | Bank.DepositMoney({ |
| 63 | target: model.accountId, |
| 64 | input: { amount: 1_000 }, |
| 65 | commandId: allocation.commandId, |
| 66 | }), |
| 67 | (result) => Message.ReceivedBankResult({ result }), |
| 68 | )], |
| 69 | }; |
| 70 | }; |
| 71 | ``` |
| 72 | |
| 73 | Handle `ReceivedBankResult` through `Bank.Message.match`. The matcher preserves each command's reply and Rejection fields. Use a named branch for every result. |
| 74 | |
| 75 | | Failure | Meaning | App action | |
| 76 | | --- | --- | --- | |
| 77 | | `Rejected { rejection }` | The aggregate refused the command. | Show the reason. | |
| 78 | | `Denied { error }` | Middleware refused the command. | Request authentication or MFA. | |
| 79 | | `Unknown` | The reply did not establish the outcome. | Retry with the same `commandId`. | |
| 80 | |
| 81 | A Command defect produces `Unknown`. Read defects call `onDefect` with their Cause. Typed read failures call `onFailure`. Interruption ends the operation without a Message. |
| 82 | |
| 83 | A lost reply can follow a committed write. Do not turn `Unknown` into a business Rejection. |
| 84 | |
| 85 | ## Follow a View's state |
| 86 | |
| 87 | ```typescript |
| 88 | import * as Option from "effect/Option"; |
| 89 | import { Subscription } from "foldkit"; |
| 90 | |
| 91 | const SummaryMessage = defineMessageUnion({ |
| 92 | ReceivedSummary: { |
| 93 | state: Schema.Option((AccountSummary.definition.state ?? Schema.Never)), |
| 94 | cursor: Schema.Number, |
| 95 | }, |
| 96 | FailedWatchSummary: { reason: Schema.String }, |
| 97 | }); |
| 98 | |
| 99 | const subscriptions = Subscription.make< |
| 100 | Model, typeof SummaryMessage.Type, typeof CustomerApi.Client.Identifier |
| 101 | >()(() => ({ |
| 102 | summary: Bank.AccountSummary.watch({ |
| 103 | key: (model: Model) => model.accountId, |
| 104 | toMessage: (snapshot): typeof SummaryMessage.Type => SummaryMessage.ReceivedSummary(snapshot), |
| 105 | onFailure: (error): typeof SummaryMessage.Type => SummaryMessage.FailedWatchSummary({ reason: error._tag }), |
| 106 | onDefect: (): typeof SummaryMessage.Type => SummaryMessage.FailedWatchSummary({ reason: "Read defect" }), |
| 107 | }), |
| 108 | })); |
| 109 | |
| 110 | const receivedSummary = (model: Model, snapshot: typeof SummaryMessage.ReceivedSummary.Type) => |
| 111 | modifyFields(model, { |
| 112 | summary: () => snapshot.state, |
| 113 | summaryCursor: () => Option.some(snapshot.cursor), |
| 114 | }); |
| 115 | ``` |
| 116 | |
| 117 | The adapter converts absent state to `Option.none()`. Store the state and cursor together. A key change restarts the watch. A cursor change does not. |
| 118 | |
| 119 | Use `isEnabled: (model) => model.online` to stop the stream while offline. A return to online restarts it with a fresh snapshot. |
| 120 | |
| 121 | Use `watch` for state. A View can change its state without an output event, so `events` cannot replace the state watch. |
| 122 | |
| 123 | ## Seed the first paint |
| 124 | |
| 125 | The server reads `client.AccountSummary.snapshot(accountId)` and encodes its state with the View's Schema. Put its `{ state, cursor }` into Flags. |
| 126 | |
| 127 | ```typescript |
| 128 | const seeded = Bank.AccountSummary.decodeSnapshotFlags(flags.summary); |
| 129 | const summary = Option.flatMap(seeded, (snapshot) => snapshot.state); |
| 130 | const summaryCursor = Option.map(seeded, (snapshot) => snapshot.cursor); |
| 131 | ``` |
| 132 | |
| 133 | Keep the outer Flags field as `Schema.Unknown`. Decode that field in `init`. A stale state Schema then falls back to empty state and a fresh watch, instead of preventing boot. |
| 134 | |
| 135 | `Bank.AccountSummary.SnapshotFlags` is the Schema for this wire shape. It decodes `null` state to `Option.none()`. Its cursor must be a nonnegative integer. |
| 136 | |
| 137 | For an event feed seeded from Flags, use the same snapshot's cursor. See [Optimistic updates](/domain/optimistic-updates#resume-the-feed). |
| 138 | |
| 139 | ## Provide the client and headers |
| 140 | |
| 141 | ```typescript |
| 142 | import * as Domain from "@alchemy.run/domain"; |
| 143 | import * as Effect from "effect/Effect"; |
| 144 | import * as Layer from "effect/Layer"; |
| 145 | import * as Socket from "effect/socket/Socket"; |
| 146 | |
| 147 | const Headers = Layer.succeed(DomainFoldkit.CommandHeaders, { |
| 148 | get: (command) => Effect.succeed( |
| 149 | command === "WithdrawMoney" ? { "x-mfa-code": "000000" } : {}, |
| 150 | ), |
| 151 | }); |
| 152 | const Connection = CustomerApi.layerClient.pipe( |
| 153 | Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)), |
| 154 | Layer.provide(Socket.layerWebSocketConstructorGlobal), |
| 155 | ); |
| 156 | const resources = Layer.merge(Connection, Headers); |
| 157 | ``` |
| 158 | |
| 159 | Provide `resources` to `Runtime.makeApplication`. The MFA value above is the bank demo's code. A real app reads the current credential at execution time. Never put credentials in Command args or Messages. |
| 160 | |
| 161 | Live reads authenticate by cookie. Serve the app and Api on one origin. WebSocket push requires a store with `connect`, such as Cloudflare Durable Objects. Use `protocolHttp` for polling on other platforms. The adapter does not select a protocol. |
| 162 | |
| 163 | ## Test and host the app |
| 164 | |
| 165 | Use `foldkit/story` to test Model changes and resolve Commands by their definitions. Use `Domain.InMemory` with the adapter's Command effects to test replies, refusals, and View reads. |
| 166 | |
| 167 | Build with `@foldkit/vite-plugin`. Host the web assets and forward `/api` to the Domain Worker on the same origin. The [bank example](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-domain) includes the runtime, offline queue, tests, and Worker. |