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

main
ts 534 lines 18.4 KB
Raw
1 import type * as Domain from "@alchemy.run/domain";
2 import * as DomainFoldkit from "@alchemy.run/domain/Foldkit";
3 import { AccountId, mainAccountId } from "@bank/domain/Account/Account.id";
4 import { StatementLine } from "@bank/domain/Account/Statement.view";
5 import { CustomerId } from "@bank/domain/Customer/Customer.id";
6 import { Username } from "@bank/domain/Customer/Username";
7 import { CustomerApi } from "@bank/domain/CustomerApi.api";
8 import * as Array from "effect/Array";
9 import * as Effect from "effect/Effect";
10 import * as Match from "effect/Match";
11 import * as Option from "effect/Option";
12 import * as Schedule from "effect/Schedule";
13 import * as Schema from "effect/Schema";
14 import * as Stream from "effect/Stream";
15 import { Command, Subscription, type Update } from "foldkit";
16 import type { Document, HtmlBuilder } from "foldkit/html";
17 import { defineMessageUnion } from "foldkit/message";
18 import { modifyFields } from "foldkit/struct";
19
20 type Bank = Domain.Api.ClientKey<"CustomerApi">;
21 export const BankClient = DomainFoldkit.make(CustomerApi);
22
23 // MODEL
24
25 export const Intent = Schema.Struct({
26 commandId: Schema.String,
27 kind: Schema.Literals(["deposit", "withdrawal"]),
28 amount: Schema.Number,
29 });
30 export type Intent = typeof Intent.Type;
31 export const intentsKey = (customerId: CustomerId) => `bank:intents:${customerId}`;
32
33 export const Flags = Schema.Struct({
34 customerId: CustomerId,
35 session: Schema.String,
36 online: Schema.Boolean,
37 intents: Schema.Array(Intent),
38 summary: Schema.optional(Schema.Unknown),
39 });
40 export type Flags = typeof Flags.Type;
41
42 export const Ack = Schema.Literals(["Pending", "Queued", "Confirmed", "Rejected", "Denied"]);
43 export type Ack = typeof Ack.Type;
44 export const Line = Schema.Struct({
45 commandId: Schema.String,
46 kind: StatementLine.fields.kind,
47 amount: Schema.Number,
48 balance: Schema.Option(Schema.Number),
49 ack: Ack,
50 reason: Schema.Option(Schema.String),
51 });
52 export type Line = typeof Line.Type;
53
54 export const Model = Schema.Struct({
55 customerId: CustomerId,
56 accountId: AccountId,
57 commandIds: DomainFoldkit.CommandIds,
58 online: Schema.Boolean,
59 balance: Schema.Option(Schema.Number),
60 summaryCursor: Schema.Option(Schema.Number),
61 statementCursor: Schema.Option(Schema.Number),
62 feedState: Schema.Literals(["CatchingUp", "Live", "Failed"]),
63 lines: Schema.Array(Line),
64 error: Schema.Option(Schema.String),
65 });
66 export type Model = typeof Model.Type;
67
68 export const Outcome = Schema.Struct({
69 commandId: Schema.String,
70 result: Schema.Literals(["Accepted", "Queued", "Rejected", "Denied"]),
71 reason: Schema.Option(Schema.String),
72 });
73 export type Outcome = typeof Outcome.Type;
74
75 // MESSAGE
76
77 export const Message = defineMessageUnion({
78 ClickedRegister: {},
79 ClickedDeposit: {},
80 ClickedWithdraw: {},
81 ClickedRetryLine: { commandId: Schema.String },
82 ReceivedBankResult: { result: BankClient.Message },
83 CompletedDeliver: { outcomes: Schema.Array(Outcome) },
84 CompletedSaveIntents: {},
85 WentOnline: {},
86 WentOffline: {},
87 ReceivedBalance: { balance: Schema.Option(Schema.Number), cursor: Schema.Number },
88 ReceivedLine: { commandId: Schema.String, line: StatementLine, cursor: Schema.Number },
89 CaughtUpStatement: { cursor: Schema.Number },
90 FailedWatchSummary: { reason: Schema.String },
91 FailedReadStatement: { reason: Schema.String },
92 });
93 export type Message = typeof Message.Type;
94
95 // COMMAND
96
97 const outcomeOfFailure = (
98 commandId: string,
99 failure: DomainFoldkit.Failure<Domain.Api.CommandsOf<typeof CustomerApi>>,
100 ) =>
101 Match.value(failure).pipe(
102 Match.withReturnType<Effect.Effect<Outcome, { readonly _tag: "Unknown" }>>(),
103 Match.tagsExhaustive({
104 Rejected: ({ rejection }) =>
105 Effect.succeed({ commandId, result: "Rejected", reason: Option.some(rejection._tag) }),
106 Denied: ({ error }) =>
107 Effect.succeed({ commandId, result: "Denied", reason: Option.some(error._tag) }),
108 Unknown: (failure) => Effect.fail(failure),
109 }),
110 );
111
112 const deliver = (accountId: AccountId, intent: Intent) => {
113 const { commandId, amount } = intent;
114 const send: Command.Command<typeof BankClient.Message.Type, never, Bank> =
115 intent.kind === "deposit"
116 ? BankClient.DepositMoney({ target: accountId, input: { amount }, commandId })
117 : BankClient.WithdrawMoney({ target: accountId, input: { amount }, commandId });
118 return send.effect.pipe(
119 Effect.flatMap((result) =>
120 Match.value(result).pipe(
121 Match.withReturnType<Effect.Effect<Outcome, { readonly _tag: "Unknown" }>>(),
122 Match.tag("FailedDepositMoney", "FailedWithdrawMoney", ({ failure }) =>
123 outcomeOfFailure(commandId, failure),
124 ),
125 Match.orElse(() =>
126 Effect.succeed({ commandId, result: "Accepted", reason: Option.none() }),
127 ),
128 ),
129 ),
130 Effect.retry({ schedule: Schedule.exponential("200 millis"), times: 3 }),
131 Effect.catch(() =>
132 Effect.succeed<Outcome>({ commandId, result: "Queued", reason: Option.none() }),
133 ),
134 );
135 };
136
137 export const Deliver = Command.define("Deliver", {
138 args: { accountId: AccountId, intents: Schema.Array(Intent) },
139 messages: [Message.CompletedDeliver],
140 execute: Effect.fn(function* ({ accountId, intents }) {
141 const outcomes: Array<Outcome> = [];
142 for (const intent of intents) {
143 const outcome = yield* deliver(accountId, intent);
144 outcomes.push(outcome);
145
146 if (outcome.result === "Queued") {
147 for (const rest of intents.slice(outcomes.length)) {
148 outcomes.push({ commandId: rest.commandId, result: "Queued", reason: Option.none() });
149 }
150 break;
151 }
152 }
153 return Message.CompletedDeliver({ outcomes });
154 }),
155 });
156
157 export const SaveIntents = Command.define("SaveIntents", {
158 args: { customerId: CustomerId, intents: Schema.Array(Intent) },
159 messages: [Message.CompletedSaveIntents],
160 execute: ({ customerId, intents }) =>
161 Effect.sync(() => {
162 localStorage.setItem(intentsKey(customerId), JSON.stringify(intents));
163 return Message.CompletedSaveIntents();
164 }),
165 });
166
167 // UPDATE
168
169 const isIntent = (line: Line): line is Line & { readonly kind: Intent["kind"] } =>
170 (line.ack === "Pending" || line.ack === "Queued") &&
171 (line.kind === "deposit" || line.kind === "withdrawal");
172 const intentsOf = (model: Model): Array<Intent> =>
173 model.lines
174 .filter(isIntent)
175 .map(({ commandId, kind, amount }) => ({ commandId, kind, amount }))
176 .reverse();
177 const save = (model: Model) =>
178 SaveIntents({ customerId: model.customerId, intents: intentsOf(model) });
179
180 const ask = (
181 model: Model,
182 kind: Intent["kind"],
183 amount: number,
184 ): Update.Return<Model, Message, Bank> => {
185 const allocation = DomainFoldkit.next(model.commandIds);
186 const { commandId } = allocation;
187 const isSending = model.online && !model.lines.some((line) => line.ack === "Queued");
188 const nextModel = modifyFields(model, {
189 commandIds: () => allocation.commandIds,
190 error: () => Option.none(),
191 lines: (lines) => [
192 Line.make({
193 commandId,
194 kind,
195 amount,
196 balance: Option.none(),
197 ack: isSending ? "Pending" : "Queued",
198 reason: Option.none(),
199 }),
200 ...lines,
201 ],
202 });
203 return {
204 model: nextModel,
205 commands: [
206 save(nextModel),
207 ...(isSending
208 ? [Deliver({ accountId: model.accountId, intents: [{ commandId, kind, amount }] })]
209 : []),
210 ],
211 };
212 };
213
214 const flush = (model: Model): Update.Return<Model, Message, Bank> => {
215 if (!model.online) {
216 return { model };
217 }
218 const queued = intentsOf(model).filter((intent) =>
219 model.lines.some((line) => line.commandId === intent.commandId && line.ack === "Queued"),
220 );
221 if (Array.isArrayEmpty(queued)) {
222 return { model };
223 }
224 const sending = new Set(queued.map((intent) => intent.commandId));
225 return {
226 model: modifyFields(model, {
227 lines: Array.map((line) =>
228 sending.has(line.commandId) ? modifyFields(line, { ack: () => "Pending" }) : line,
229 ),
230 }),
231 commands: [Deliver({ accountId: model.accountId, intents: queued })],
232 };
233 };
234
235 const delivered = (model: Model, outcomes: ReadonlyArray<Outcome>): Model => {
236 const byId = new Map(outcomes.map((outcome) => [outcome.commandId, outcome]));
237 return modifyFields(model, {
238 lines: Array.map((line) => {
239 const outcome = byId.get(line.commandId);
240 if (!outcome || line.ack === "Confirmed") {
241 return line;
242 }
243 return Match.value(outcome.result).pipe(
244 Match.withReturnType<Line>(),
245 Match.when("Accepted", () => line),
246 Match.when("Queued", () => modifyFields(line, { ack: () => "Queued" })),
247 Match.when("Denied", () =>
248 modifyFields(line, { ack: () => "Denied", reason: () => outcome.reason }),
249 ),
250 Match.when("Rejected", () =>
251 modifyFields(line, { ack: () => "Rejected", reason: () => outcome.reason }),
252 ),
253 Match.exhaustive,
254 );
255 }),
256 });
257 };
258
259 const confirm = (model: Model, commandId: string, line: StatementLine, cursor: number): Model => {
260 const confirmed = Line.make({
261 commandId,
262 kind: line.kind,
263 amount: line.amount,
264 balance: Option.some(line.balance),
265 ack: "Confirmed",
266 reason: Option.none(),
267 });
268 const others = model.lines.filter((line) => line.commandId !== commandId);
269 return modifyFields(model, {
270 lines: () => [
271 ...others.filter((line) => line.ack !== "Confirmed"),
272 confirmed,
273 ...others.filter((line) => line.ack === "Confirmed"),
274 ],
275 statementCursor: () => Option.some(cursor),
276 });
277 };
278
279 export const update = (model: Model, message: Message) =>
280 Message.match<Update.Return<Model, Message, Bank>>(message, {
281 ClickedRegister: () => {
282 const allocation = DomainFoldkit.next(model.commandIds);
283 return {
284 model: modifyFields(model, { commandIds: () => allocation.commandIds }),
285 commands: [
286 Command.mapMessage(
287 BankClient.RegisterCustomer({
288 target: model.customerId,
289 input: { name: model.customerId, username: Username.make(model.customerId) },
290 commandId: allocation.commandId,
291 }),
292 (result) => Message.ReceivedBankResult({ result }),
293 ),
294 ],
295 };
296 },
297 ClickedDeposit: () => ask(model, "deposit", 1_000),
298 ClickedWithdraw: () => ask(model, "withdrawal", 1_000),
299 ClickedRetryLine: ({ commandId }) => {
300 const retry = flush(
301 modifyFields(model, {
302 lines: Array.map((line) =>
303 line.commandId === commandId && line.ack === "Denied"
304 ? modifyFields(line, { ack: () => "Queued", reason: () => Option.none() })
305 : line,
306 ),
307 }),
308 );
309 return { model: retry.model, commands: [save(retry.model), ...(retry.commands ?? [])] };
310 },
311 ReceivedBankResult: ({ result }) =>
312 Match.value(result).pipe(
313 Match.withReturnType<Update.Return<Model, Message, Bank>>(),
314 Match.tag("FailedRegisterCustomer", ({ failure }) => ({
315 model: modifyFields(model, { error: () => Option.some(failure._tag) }),
316 })),
317 Match.orElse(() => ({ model: modifyFields(model, { error: () => Option.none() }) })),
318 ),
319 CompletedDeliver: ({ outcomes }) => {
320 const nextModel = delivered(model, outcomes);
321 return { model: nextModel, commands: [save(nextModel)] };
322 },
323 CompletedSaveIntents: () => ({ model }),
324 WentOnline: () => flush(modifyFields(model, { online: () => true })),
325 WentOffline: () => ({
326 model: modifyFields(model, { online: () => false, feedState: () => "CatchingUp" }),
327 }),
328 ReceivedBalance: ({ balance, cursor }) => ({
329 model: modifyFields(model, {
330 balance: () => balance,
331 summaryCursor: () => Option.some(cursor),
332 }),
333 }),
334 ReceivedLine: ({ commandId, line, cursor }) => {
335 const nextModel = confirm(model, commandId, line, cursor);
336 return { model: nextModel, commands: [save(nextModel)] };
337 },
338 CaughtUpStatement: ({ cursor }) => ({
339 model: modifyFields(model, {
340 statementCursor: () => Option.some(cursor),
341 feedState: () => "Live",
342 }),
343 }),
344 FailedWatchSummary: ({ reason }) => ({
345 model: modifyFields(model, { error: () => Option.some(reason) }),
346 }),
347 FailedReadStatement: ({ reason }) => ({
348 model: modifyFields(model, { error: () => Option.some(reason), feedState: () => "Failed" }),
349 }),
350 });
351
352 // INIT
353
354 export const init = (flags: Flags): Update.Return<Model, Message, Bank> => {
355 const summary = BankClient.AccountSummary.decodeSnapshotFlags(flags.summary);
356 const model = Model.make({
357 customerId: flags.customerId,
358 accountId: mainAccountId(flags.customerId),
359 commandIds: { session: flags.session, sent: 0 },
360 online: flags.online,
361 balance: Option.flatMap(summary, (snapshot) =>
362 Option.map(snapshot.state, (state) => state.balance),
363 ),
364 summaryCursor: Option.map(summary, (snapshot) => snapshot.cursor),
365 statementCursor: Option.none(),
366 feedState: "CatchingUp",
367 lines: flags.intents
368 .map((intent) =>
369 Line.make({ ...intent, balance: Option.none(), ack: "Queued", reason: Option.none() }),
370 )
371 .reverse(),
372 error: Option.none(),
373 });
374 return model.online ? flush(model) : { model };
375 };
376
377 // SUBSCRIPTION
378
379 export const subscriptions = Subscription.make<Model, Message, Bank>()((entry) => ({
380 connectivity: entry(
381 {},
382 {
383 modelToDependencies: () => ({}),
384 dependenciesToStream: () =>
385 Stream.merge(
386 Stream.fromEventListener(window, "online").pipe(Stream.as(Message.WentOnline())),
387 Stream.fromEventListener(window, "offline").pipe(Stream.as(Message.WentOffline())),
388 ),
389 },
390 ),
391 summary: BankClient.AccountSummary.watch({
392 key: (model: Model) => model.accountId,
393 isEnabled: (model) => model.online,
394 toMessage: ({ state, cursor }): Message =>
395 Message.ReceivedBalance({ balance: Option.map(state, (summary) => summary.balance), cursor }),
396 onFailure: (error): Message => Message.FailedWatchSummary({ reason: error._tag }),
397 onDefect: (): Message => Message.FailedWatchSummary({ reason: "Read defect" }),
398 }),
399 statement: BankClient.Statement.events({
400 key: (model: Model) => model.accountId,
401 cursor: (model) => model.statementCursor,
402 isEnabled: (model) => model.online,
403 onEntry: ({ event, envelope }): Message =>
404 Message.ReceivedLine({ commandId: envelope.commandId, line: event, cursor: envelope.seq }),
405 onCaughtUp: (cursor): Message => Message.CaughtUpStatement({ cursor }),
406 onFailure: (error): Message => Message.FailedReadStatement({ reason: error._tag }),
407 onDefect: (): Message => Message.FailedReadStatement({ reason: "Read defect" }),
408 }),
409 }));
410
411 // VIEW
412
413 const signed = (line: Line) =>
414 line.kind === "deposit" ||
415 line.kind === "transfer-in" ||
416 line.kind === "refund" ||
417 line.kind === "settlement"
418 ? line.amount
419 : -line.amount;
420
421 export const shownBalance = (model: Model): Option.Option<number> =>
422 Option.map(model.balance, (balance) => {
423 const confirmed = Option.flatMap(
424 Array.findFirst(model.lines, (line) => line.ack === "Confirmed"),
425 (line) => line.balance,
426 );
427 return model.lines
428 .filter((line) => line.ack === "Pending" || line.ack === "Queued")
429 .reduce(
430 (sum, line) => sum + signed(line),
431 Option.getOrElse(confirmed, () => balance),
432 );
433 });
434 const button = "bg-black text-white hover:bg-gray-700 px-4 py-2";
435 const cents = (amount: number) => (amount / 100).toFixed(2);
436 const lineView = (line: Line, h: HtmlBuilder<Message>) => {
437 const text = `${line.kind} ${cents(line.amount)}`;
438 const item = h.keyed("li");
439 return Match.value(line.ack).pipe(
440 Match.when("Pending", () =>
441 item(line.commandId, [h.Class("text-gray-400 italic")], [`${text}, sending`]),
442 ),
443 Match.when("Queued", () =>
444 item(line.commandId, [h.Class("text-amber-600 italic")], [`${text}, queued until online`]),
445 ),
446 Match.when("Denied", () =>
447 item(
448 line.commandId,
449 [h.Class("text-amber-600")],
450 [
451 `${text}, authentication required: ${Option.getOrElse(line.reason, () => "Denied")}`,
452 h.button(
453 [h.OnClick(Message.ClickedRetryLine({ commandId: line.commandId })), h.Class(button)],
454 ["Retry"],
455 ),
456 ],
457 ),
458 ),
459 Match.when("Rejected", () =>
460 item(
461 line.commandId,
462 [h.Class("text-red-600 line-through")],
463 [`${text}, rejected: ${Option.getOrElse(line.reason, () => "Rejected")}`],
464 ),
465 ),
466 Match.when("Confirmed", () =>
467 item(
468 line.commandId,
469 [],
470 [
471 `${text}, balance ${Option.match(line.balance, { onNone: () => "unknown", onSome: cents })}`,
472 ],
473 ),
474 ),
475 Match.exhaustive,
476 );
477 };
478 export const view = (model: Model, h: HtmlBuilder<Message>): Document => {
479 const balance = shownBalance(model);
480 const isUnacknowledged = model.lines.some(
481 (line) => line.ack === "Pending" || line.ack === "Queued",
482 );
483 return {
484 title: Option.match(balance, {
485 onNone: () => "Bank",
486 onSome: (amount) => `Balance: ${cents(amount)}`,
487 }),
488 body: h.div(
489 [h.Class("flex flex-col gap-4 p-8")],
490 [
491 h.p([], [`Signed in as ${model.customerId}`]),
492 ...(model.online
493 ? []
494 : [
495 h.p(
496 [h.Class("text-amber-600")],
497 ["Offline: changes are kept and sent when you reconnect."],
498 ),
499 ]),
500 ...Option.match(balance, {
501 onNone: () => [
502 h.button([h.OnClick(Message.ClickedRegister()), h.Class(button)], ["Open my account"]),
503 ],
504 onSome: (amount) => [
505 h.div(
506 [
507 h.Class(
508 isUnacknowledged ? "text-4xl font-bold text-gray-400" : "text-4xl font-bold",
509 ),
510 ],
511 [isUnacknowledged ? `${cents(amount)} (pending)` : cents(amount)],
512 ),
513 h.div(
514 [h.Class("flex gap-2")],
515 [
516 h.button([h.OnClick(Message.ClickedDeposit()), h.Class(button)], ["Deposit 10.00"]),
517 h.button(
518 [h.OnClick(Message.ClickedWithdraw()), h.Class(button)],
519 ["Withdraw 10.00"],
520 ),
521 ],
522 ),
523 ],
524 }),
525 h.p([], [model.feedState === "Live" ? "Statement is live" : "Statement is catching up"]),
526 h.p([h.Class("text-red-600")], [Option.getOrElse(model.error, () => "")]),
527 h.ul(
528 [],
529 model.lines.map((line) => lineView(line, h)),
530 ),
531 ],
532 ),
533 };
534 };