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

main
ts 161 lines 5.74 KB
Raw
1 import type * as Domain from "@alchemy.run/domain";
2 import * as Effect from "effect/Effect";
3 import * as Schema from "effect/Schema";
4 import * as Stream from "effect/Stream";
5 import { Command, Subscription, type Update } from "foldkit";
6 import type { Document, HtmlBuilder } from "foldkit/html";
7 import { defineMessageUnion } from "foldkit/message";
8 import { NotesApi } from "../NotesApi.api.ts";
9 import { UserId } from "../User.id.ts";
10 import { auth } from "./auth.ts";
11
12 // The services the app's commands and subscriptions use: the NotesApi client.
13 type Notes = Domain.Api.ClientKey<"NotesApi">;
14
15 const User = Schema.Struct({ userId: UserId, name: Schema.String });
16
17 /** Who better-auth says is signed in when the page loads, or `null`. */
18 export const Flags = Schema.Struct({ user: Schema.NullOr(User) });
19 export type Flags = typeof Flags.Type;
20
21 export const Model = Schema.Struct({
22 user: Schema.NullOr(User),
23 draft: Schema.String,
24 notes: Schema.Array(Schema.String),
25 error: Schema.NullOr(Schema.String),
26 });
27 export type Model = typeof Model.Type;
28
29 const Provider = Schema.Literals(["github", "google"]);
30
31 export const Message = defineMessageUnion({
32 ClickedSignIn: { provider: Provider },
33 ClickedSignOut: {},
34 ChangedDraft: { text: Schema.String },
35 SubmittedNote: {},
36 Saved: {},
37 Failed: { reason: Schema.String },
38 GotNotes: { notes: Schema.Array(Schema.String) },
39 });
40 export type Message = typeof Message.Type;
41
42 /** Send the browser to GitHub or Google; better-auth brings it back to `/` signed in. */
43 export const SignIn = Command.define("SignIn", {
44 args: { provider: Provider },
45 messages: [Message.Failed],
46 execute: ({ provider }) =>
47 Effect.promise(() => auth.signIn.social({ provider, callbackURL: "/" })).pipe(
48 Effect.map((result) => Message.Failed({ reason: result.error?.message ?? "Redirecting" })),
49 ),
50 });
51
52 /** Clear better-auth's session, then start over signed out. */
53 export const SignOut = Command.define("SignOut", {
54 args: {},
55 messages: [Message.Failed],
56 execute: () =>
57 Effect.promise(() => auth.signOut()).pipe(
58 Effect.flatMap(() => Effect.sync(() => location.reload())),
59 Effect.as(Message.Failed({ reason: "Signing out" })),
60 ),
61 });
62
63 /** Write a note in the user's notebook. The session cookie goes with the call. */
64 export const WriteNote = Command.define("WriteNote", {
65 args: { userId: UserId, text: Schema.String },
66 messages: [Message.Saved, Message.Failed],
67 execute: ({ userId, text }) =>
68 Effect.gen(function* () {
69 const notes = yield* NotesApi.Client;
70 yield* notes.WriteNote(userId, { text });
71 return Message.Saved();
72 }).pipe(Effect.catch((error) => Effect.succeed(Message.Failed({ reason: error._tag })))),
73 });
74
75 export const update = (model: Model, message: Message): Update.Return<Model, Message, Notes> =>
76 Message.match<Update.Return<Model, Message, Notes>>(message, {
77 ClickedSignIn: ({ provider }) => ({ model, commands: [SignIn({ provider })] }),
78 ClickedSignOut: () => ({ model, commands: [SignOut({})] }),
79 ChangedDraft: ({ text }) => ({ model: { ...model, draft: text } }),
80 SubmittedNote: () =>
81 model.user === null || model.draft.trim() === ""
82 ? { model }
83 : {
84 model: { ...model, draft: "" },
85 commands: [WriteNote({ userId: model.user.userId, text: model.draft })],
86 },
87 // The note arrives through the subscription; success only clears an error.
88 Saved: () => ({ model: { ...model, error: null } }),
89 Failed: ({ reason }) => ({ model: { ...model, error: reason } }),
90 GotNotes: ({ notes }) => ({ model: { ...model, notes } }),
91 });
92
93 export const init = (flags: Flags): Update.Return<Model, Message, Notes> => ({
94 model: { user: flags.user, draft: "", notes: [], error: null },
95 });
96
97 export const subscriptions = Subscription.make<Model, Message, Notes>()((entry) => ({
98 notes: entry(
99 { userId: Schema.NullOr(UserId) },
100 {
101 modelToDependencies: (model) => ({ userId: model.user?.userId ?? null }),
102 dependenciesToStream: ({ userId }) =>
103 userId === null
104 ? Stream.empty
105 : Stream.unwrap(
106 Effect.gen(function* () {
107 const notes = yield* NotesApi.Client;
108 return notes.Notes.watch(userId);
109 }),
110 ).pipe(
111 Stream.map(({ state }) => Message.GotNotes({ notes: state?.notes ?? [] })),
112 Stream.catch((error) => Stream.succeed(Message.Failed({ reason: error._tag }))),
113 ),
114 },
115 ),
116 }));
117
118 export const view = (model: Model, h: HtmlBuilder<Message>): Document => ({
119 title: "Notes",
120 body:
121 model.user === null
122 ? h.div(
123 [],
124 [
125 h.h1([], ["Notes"]),
126 h.button(
127 [h.OnClick(Message.ClickedSignIn({ provider: "github" }))],
128 ["Sign in with GitHub"],
129 ),
130 h.button(
131 [h.OnClick(Message.ClickedSignIn({ provider: "google" }))],
132 ["Sign in with Google"],
133 ),
134 h.p([], [model.error ?? ""]),
135 ],
136 )
137 : h.div(
138 [],
139 [
140 h.h1([], ["Notes"]),
141 h.p([], [`Signed in as ${model.user.name}`]),
142 h.form(
143 [h.OnSubmit(Message.SubmittedNote())],
144 [
145 h.input([
146 h.Value(model.draft),
147 h.Placeholder("Write a note"),
148 h.OnInput((text) => Message.ChangedDraft({ text })),
149 ]),
150 h.button([h.Type("submit")], ["Save"]),
151 ],
152 ),
153 h.ul(
154 [],
155 model.notes.map((note) => h.li([], [note])),
156 ),
157 h.button([h.OnClick(Message.ClickedSignOut())], ["Sign out"]),
158 h.p([], [model.error ?? ""]),
159 ],
160 ),
161 });