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

main
ts 477 lines 18.4 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import * as Foldkit from "@alchemy.run/domain/Foldkit";
3 import { describe, expect, it } from "@alchemy.run/test";
4 import * as Cause from "effect/Cause";
5 import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 import * as RpcClientError from "effect/rpc/RpcClientError";
11 import * as Schema from "effect/Schema";
12 import * as Stream from "effect/Stream";
13 import {
14 Client,
15 Counter as CounterAggregate,
16 CounterApi,
17 CounterId,
18 Increment,
19 } from "./FoldkitCounter.ts";
20
21 const Counter = Foldkit.make(CounterApi);
22 const target = CounterId.make("one");
23
24 describe("Domain Foldkit", { tags: ["unit", "local"] }, () => {
25 it.live("keeps reply, receipt and the caller's id on success", () =>
26 Effect.gen(function* () {
27 const result = yield* Counter.Increment({ target, input: { amount: 2 }, commandId: "page:0" })
28 .effect;
29 expect(result).toEqual({
30 _tag: "SucceededIncrement",
31 commandId: "page:0",
32 reply: { total: 2 },
33 receipt: { stream: "Counter/one", version: 1 },
34 });
35 expect(Schema.is(Counter.Message)(result)).toBe(true);
36 const replay = yield* Counter.Increment({ target, input: { amount: 2 }, commandId: "page:0" })
37 .effect;
38 expect(replay).toEqual(result);
39 }).pipe(Effect.provide(Client)),
40 );
41
42 it.live("keeps declared rejection fields", () =>
43 Effect.gen(function* () {
44 const result = yield* Counter.Increment({
45 target,
46 input: { amount: 11 },
47 commandId: "page:1",
48 }).effect;
49 expect(result).toMatchObject({
50 _tag: "FailedIncrement",
51 commandId: "page:1",
52 failure: { _tag: "Rejected", rejection: { _tag: "Limit", amount: 11 } },
53 });
54 }).pipe(Effect.provide(Client)),
55 );
56
57 it.live("classifies a middleware refusal as Denied", () =>
58 Effect.gen(function* () {
59 const result = yield* Counter.Reset({ target, input: {}, commandId: "page:2" }).effect;
60 expect(result).toMatchObject({
61 _tag: "FailedReset",
62 failure: { _tag: "Denied", error: { _tag: "Unauthenticated" } },
63 });
64 }).pipe(Effect.provide(Client)),
65 );
66
67 it.live("keeps transport uncertainty and reads headers only during execution", () =>
68 Effect.gen(function* () {
69 const client = yield* CounterApi.Client;
70 let calls = 0;
71 const uncertain = Layer.succeed(CounterApi.Client, {
72 ...client,
73 // The server applies the command; its reply is lost on the way back.
74 Increment: (...args: Parameters<typeof client.Increment>) =>
75 client.Increment(...args).pipe(
76 Effect.andThen(
77 Effect.fail(
78 new RpcClientError.RpcClientError({
79 reason: new RpcClientError.RpcClientDefect({
80 cause: "lost reply",
81 message: "lost reply",
82 }),
83 }),
84 ),
85 ),
86 ),
87 });
88 const command = Counter.Increment({ target, input: { amount: 1 }, commandId: "page:3" });
89 expect(calls).toBe(0);
90 const result = yield* command.effect.pipe(
91 Effect.provide(uncertain),
92 Effect.provideService(Foldkit.CommandHeaders, {
93 get: () =>
94 Effect.sync(() => {
95 calls += 1;
96 return { "x-mfa-code": "secret" };
97 }),
98 }),
99 );
100 expect(calls).toBe(1);
101 expect(result).toMatchObject({ _tag: "FailedIncrement", failure: { _tag: "Unknown" } });
102 expect(command.args).toEqual({ target, input: { amount: 1 }, commandId: "page:3" });
103 }).pipe(Effect.provide(Client)),
104 );
105
106 it.live("turns a defect while reading headers into Unknown", () =>
107 Effect.gen(function* () {
108 const result = yield* Counter.Increment({
109 target,
110 input: { amount: 1 },
111 commandId: "page:4",
112 }).effect.pipe(
113 Effect.provideService(Foldkit.CommandHeaders, {
114 get: () => Effect.die("storage unavailable"),
115 }),
116 );
117 expect(result).toMatchObject({ _tag: "FailedIncrement", failure: { _tag: "Unknown" } });
118 }).pipe(Effect.provide(Client)),
119 );
120
121 it("allocates ids without changing the prior state", () => {
122 const ids = Foldkit.CommandIds.make({ session: "page", sent: 0 });
123 expect(Foldkit.next(ids)).toEqual({
124 commandId: "page:0",
125 commandIds: { session: "page", sent: 1 },
126 });
127 expect(ids.sent).toBe(0);
128 });
129
130 const watched = Counter.Total.watch({
131 key: (model: { id: typeof CounterId.Type; cursor: number; online: boolean }) => model.id,
132 isEnabled: (model) => model.online,
133 toMessage: (snapshot) => ({ _tag: "ReceivedTotal", snapshot }),
134 onFailure: () => ({ _tag: "ReceivedTotal", snapshot: { state: Option.none(), cursor: 0 } }),
135 onDefect: () => ({ _tag: "ReceivedTotal", snapshot: { state: Option.none(), cursor: 0 } }),
136 });
137
138 it.live("watches absent state as None and preserves the cursor", () =>
139 watched.dependenciesToStream({ key: target, isEnabled: true }).pipe(
140 Stream.take(1),
141 Stream.runCollect,
142 Effect.tap((messages) =>
143 Effect.sync(() =>
144 expect(messages).toEqual([
145 { _tag: "ReceivedTotal", snapshot: { state: Option.none(), cursor: 0 } },
146 ]),
147 ),
148 ),
149 Effect.asVoid,
150 Effect.provide(Client),
151 ),
152 );
153
154 it.live("watches a fresh state and cursor after a write", () =>
155 Effect.gen(function* () {
156 const reply = yield* Counter.Increment({ target, input: { amount: 2 }, commandId: "page:0" })
157 .effect;
158 if (reply._tag === "SucceededIncrement") {
159 const client = yield* CounterApi.Client;
160 yield* client.Total.snapshot(target, { atLeast: reply.receipt });
161 }
162 const messages = yield* watched
163 .dependenciesToStream({ key: target, isEnabled: true })
164 .pipe(Stream.take(1), Stream.runCollect);
165 expect(messages).toEqual([
166 { _tag: "ReceivedTotal", snapshot: { state: Option.some({ total: 2 }), cursor: 1 } },
167 ]);
168 }).pipe(Effect.provide(Client)),
169 );
170
171 it("restarts for key or enabled changes and ignores Model cursor changes", () => {
172 const model = { id: target, cursor: 0, online: true };
173 expect(watched.modelToDependencies(model)).toEqual(
174 watched.modelToDependencies({ ...model, cursor: 4 }),
175 );
176 expect(watched.modelToDependencies(model)).not.toEqual(
177 watched.modelToDependencies({ ...model, id: CounterId.make("two") }),
178 );
179 });
180
181 it.live("does not open a disabled watch", () =>
182 watched.dependenciesToStream({ key: target, isEnabled: false }).pipe(
183 Stream.runCollect,
184 Effect.tap((messages) => Effect.sync(() => expect(messages).toEqual([]))),
185 Effect.asVoid,
186 Effect.provide(Client),
187 ),
188 );
189
190 type FeedModel = { id: typeof CounterId.Type; cursor: Option.Option<number>; online: boolean };
191 const feed = Counter.Total.events({
192 key: (model: FeedModel) => model.id,
193 cursor: (model) => model.cursor,
194 isEnabled: (model) => model.online,
195 onEntry: (entry) => `entry:${entry.envelope.seq}:${entry.envelope.commandId}`,
196 onCaughtUp: (cursor) => `caught:${cursor}`,
197 onFailure: (error) => `failed:${error._tag}`,
198 onDefect: () => "defect",
199 });
200 const dependencies = { key: target, cursor: Option.none<number>(), isEnabled: true };
201
202 it.live("resumes from the latest Model cursor and preserves source command ids", () =>
203 Effect.gen(function* () {
204 const client = yield* CounterApi.Client;
205 const receipt = yield* client.Increment(target, { amount: 2 }, { commandId: "page:0" });
206 yield* client.Increment(target, { amount: 3 }, { commandId: "page:1" });
207 yield* client.Total.snapshot(target, { atLeast: { stream: receipt.stream, version: 2 } });
208 const messages = yield* feed
209 .dependenciesToStream(dependencies, () => ({ ...dependencies, cursor: Option.some(1) }))
210 .pipe(Stream.take(2), Stream.runCollect);
211 expect(messages).toEqual(["entry:2:page:1", "caught:2"]);
212 }).pipe(Effect.provide(Client)),
213 );
214
215 it.live("drops duplicate entries while allowing gaps in filtered feeds", () =>
216 Effect.gen(function* () {
217 const client = yield* CounterApi.Client;
218 const receipt = yield* client.Increment(target, { amount: 2 }, { commandId: "page:0" });
219 yield* client.Total.snapshot(target, { atLeast: receipt });
220 const frames = yield* client.Total.events(target).pipe(Stream.take(2), Stream.runCollect);
221 const entries = frames.filter(Domain.Read.isEvent);
222 const replay = entries.flatMap((entry) => [
223 entry,
224 entry,
225 { ...entry, envelope: { ...entry.envelope, seq: 5 } },
226 ]);
227 const source = Layer.succeed(CounterApi.Client, {
228 ...client,
229 Total: { ...client.Total, events: () => Stream.fromIterable(replay) },
230 });
231 const messages = yield* feed
232 .dependenciesToStream(dependencies, () => dependencies)
233 .pipe(Stream.runCollect, Effect.provide(source));
234 expect(messages).toEqual(["entry:1:page:0", "entry:5:page:0"]);
235 }).pipe(Effect.provide(Client)),
236 );
237
238 it("keeps the event stream alive across cursor changes", () => {
239 expect(
240 feed.keepAliveEquivalence(dependencies, { ...dependencies, cursor: Option.some(5) }),
241 ).toBe(true);
242 expect(
243 feed.keepAliveEquivalence(dependencies, { ...dependencies, key: CounterId.make("two") }),
244 ).toBe(false);
245 expect(feed.keepAliveEquivalence(dependencies, { ...dependencies, isEnabled: false })).toBe(
246 false,
247 );
248 });
249
250 it("decodes snapshot Flags and falls back when their state Schema changed", () => {
251 expect(Counter.Total.decodeSnapshotFlags({ state: { total: 4 }, cursor: 7 })).toEqual(
252 Option.some({ state: Option.some({ total: 4 }), cursor: 7 }),
253 );
254 expect(Counter.Total.decodeSnapshotFlags({ state: null, cursor: 0 })).toEqual(
255 Option.some({ state: Option.none(), cursor: 0 }),
256 );
257 expect(Counter.Total.decodeSnapshotFlags({ state: { oldTotal: 4 }, cursor: 7 })).toEqual(
258 Option.none(),
259 );
260 expect(Counter.Total.decodeSnapshotFlags({ state: null, cursor: -1 })).toEqual(Option.none());
261 expect(Counter.Total.decodeSnapshotFlags(undefined)).toEqual(Option.none());
262 });
263
264 it("can restart a failed Flags cursor without changing the View key", () => {
265 expect(
266 feed.keepAliveEquivalence(
267 { ...dependencies, restartKey: 0 },
268 { ...dependencies, cursor: Option.none(), restartKey: 1 },
269 ),
270 ).toBe(false);
271 });
272
273 it.live("turns a mid-stream validate refusal into an app Message", () =>
274 Effect.gen(function* () {
275 const started = yield* Deferred.make<void>();
276 const read = Counter.Total.watch({
277 key: () => target,
278 toMessage: (snapshot) => `snapshot:${snapshot.cursor}`,
279 onFailure: (error) => `failed:${error._tag}`,
280 onDefect: () => "defect",
281 });
282 const watch = yield* read.dependenciesToStream({ key: target, isEnabled: true }).pipe(
283 Stream.tap(() => Deferred.succeed(started, undefined)),
284 Stream.runCollect,
285 Effect.forkChild,
286 );
287 yield* Deferred.await(started);
288 yield* Counter.Increment({ target, input: { amount: 6 }, commandId: "page:0" }).effect;
289 expect(yield* Fiber.join(watch)).toEqual(["snapshot:0", "failed:Limit"]);
290 const messages = yield* feed
291 .dependenciesToStream(dependencies, () => dependencies)
292 .pipe(Stream.runCollect);
293 expect(messages).toEqual(["failed:Limit"]);
294 }).pipe(Effect.scoped, Effect.provide(Client)),
295 );
296
297 it.live("maps command defects to Unknown and preserves interruption", () =>
298 Effect.gen(function* () {
299 const client = yield* CounterApi.Client;
300 const command = Counter.Increment({ target, input: { amount: 1 }, commandId: "page:die" });
301 const source = Layer.succeed(CounterApi.Client, {
302 ...client,
303 Increment: (...args: Parameters<typeof client.Increment>) =>
304 client.Increment(...args).pipe(Effect.andThen(Effect.die("storage failed"))),
305 });
306 const result = yield* command.effect.pipe(Effect.provide(source));
307 expect(result).toMatchObject({ _tag: "FailedIncrement", failure: { _tag: "Unknown" } });
308 const interrupted = Layer.succeed(CounterApi.Client, {
309 ...client,
310 Increment: (...args: Parameters<typeof client.Increment>) =>
311 client.Increment(...args).pipe(Effect.andThen(Effect.interrupt)),
312 });
313 const exit = yield* command.effect.pipe(Effect.provide(interrupted), Effect.exit);
314 expect(exit._tag).toBe("Failure");
315 if (exit._tag === "Failure") {
316 expect(Cause.hasInterrupts(exit.cause)).toBe(true);
317 }
318 }).pipe(Effect.provide(Client)),
319 );
320
321 it.live("turns watch and event defects into Messages", () =>
322 Effect.gen(function* () {
323 const client = yield* CounterApi.Client;
324 const source = Layer.succeed(CounterApi.Client, {
325 ...client,
326 Total: {
327 ...client.Total,
328 watch: (...args: Parameters<typeof client.Total.watch>) =>
329 client.Total.watch(...args).pipe(
330 Stream.take(1),
331 Stream.concat(Stream.die("watch failed")),
332 ),
333 events: (...args: Parameters<typeof client.Total.events>) =>
334 client.Total.events(...args).pipe(
335 Stream.take(1),
336 Stream.concat(Stream.die("events failed")),
337 ),
338 },
339 });
340 const read = Counter.Total.watch({
341 key: () => target,
342 toMessage: () => "snapshot",
343 onFailure: () => "failure",
344 onDefect: (cause) => (Cause.pretty(cause).includes("watch failed") ? "defect" : "other"),
345 });
346 expect(
347 yield* read
348 .dependenciesToStream({ key: target, isEnabled: true })
349 .pipe(Stream.runCollect, Effect.provide(source)),
350 ).toEqual(["snapshot", "defect"]);
351 expect(
352 yield* feed
353 .dependenciesToStream(dependencies, () => dependencies)
354 .pipe(Stream.runCollect, Effect.provide(source)),
355 ).toEqual(["caught:0", "defect"]);
356 }).pipe(Effect.provide(Client)),
357 );
358
359 it.live("preserves interruption in watch and event streams", () =>
360 Effect.gen(function* () {
361 const client = yield* CounterApi.Client;
362 const source = Layer.succeed(CounterApi.Client, {
363 ...client,
364 Total: {
365 ...client.Total,
366 watch: (...args: Parameters<typeof client.Total.watch>) =>
367 client.Total.watch(...args).pipe(
368 Stream.take(1),
369 Stream.concat(Stream.fromEffect(Effect.interrupt)),
370 ),
371 events: (...args: Parameters<typeof client.Total.events>) =>
372 client.Total.events(...args).pipe(
373 Stream.take(1),
374 Stream.concat(Stream.fromEffect(Effect.interrupt)),
375 ),
376 },
377 });
378 const reads = [
379 watched.dependenciesToStream({ key: target, isEnabled: true }).pipe(Stream.runDrain),
380 feed.dependenciesToStream(dependencies, () => dependencies).pipe(Stream.runDrain),
381 ];
382 for (const read of reads) {
383 const exit = yield* read.pipe(Effect.provide(source), Effect.exit);
384 expect(exit._tag).toBe("Failure");
385 if (exit._tag === "Failure") {
386 expect(Cause.hasInterrupts(exit.cause)).toBe(true);
387 }
388 }
389 }).pipe(Effect.provide(Client)),
390 );
391
392 it.live("watches Aggregate state and follows committed events", () =>
393 Effect.gen(function* () {
394 yield* Counter.Increment({ target, input: { amount: 3 }, commandId: "page:aggregate" })
395 .effect;
396 const watch = Counter.Counter.watch({
397 key: () => target,
398 toMessage: (snapshot) => snapshot,
399 onFailure: () => ({ state: Option.none(), cursor: -1 }),
400 onDefect: () => ({ state: Option.none(), cursor: -1 }),
401 });
402 const snapshots = yield* watch
403 .dependenciesToStream({ key: target, isEnabled: true })
404 .pipe(Stream.take(1), Stream.runCollect);
405 expect(snapshots).toEqual([{ state: Option.some({ total: 3 }), cursor: 1 }]);
406 const feed = Counter.Counter.events({
407 key: () => target,
408 cursor: () => Option.none(),
409 onEntry: (entry) => entry.event.amount,
410 onCaughtUp: (cursor) => cursor,
411 onFailure: () => -1,
412 onDefect: () => -1,
413 });
414 const dependencies = feed.modelToDependencies(undefined);
415 const events = yield* feed
416 .dependenciesToStream(dependencies, () => dependencies)
417 .pipe(Stream.take(2), Stream.runCollect);
418 expect(events).toEqual([3, 1]);
419 }).pipe(Effect.provide(Client)),
420 );
421
422 it.live("watches Stream absence and reports CaughtUp", () =>
423 Effect.gen(function* () {
424 const watch = Counter.Outputs.watch({
425 key: () => target,
426 toMessage: (snapshot) => snapshot,
427 onFailure: () => ({ state: Option.none(), cursor: -1 }),
428 onDefect: () => ({ state: Option.none(), cursor: -1 }),
429 });
430 const snapshots = yield* watch
431 .dependenciesToStream({ key: target, isEnabled: true })
432 .pipe(Stream.take(1), Stream.runCollect);
433 expect(snapshots).toEqual([{ state: Option.none(), cursor: 0 }]);
434 const feed = Counter.Outputs.events({
435 key: () => target,
436 cursor: () => Option.none(),
437 onEntry: (entry) => entry.event.amount,
438 onCaughtUp: (cursor) => cursor,
439 onFailure: () => -1,
440 onDefect: () => -1,
441 });
442 const dependencies = feed.modelToDependencies(undefined);
443 const events = yield* feed
444 .dependenciesToStream(dependencies, () => dependencies)
445 .pipe(Stream.take(1), Stream.runCollect);
446 expect(events).toEqual([0]);
447 }).pipe(Effect.provide(Client)),
448 );
449
450 it("reserves Message for command results", () => {
451 class MessageView extends Domain.View("Message", {
452 from: [],
453 key: Schema.String,
454 state: Schema.Number,
455 initial: 0,
456 }) {}
457 class Collision extends Domain.Model("Collision", {
458 aggregates: [CounterAggregate],
459 views: [MessageView],
460 }) {}
461 class CollisionApi extends Domain.Api("CollisionApi", {
462 model: Collision,
463 commands: ["Increment"],
464 views: ["Message"],
465 }) {}
466 // @ts-expect-error Message is reserved for command results
467 const collision = Foldkit.make(CollisionApi);
468 expect("watch" in collision.Message).toBe(false);
469 expect(
470 Schema.is(collision.Message)({
471 _tag: "FailedIncrement",
472 commandId: "page:0",
473 failure: { _tag: "Unknown" },
474 }),
475 ).toBe(true);
476 });
477 });