Skip to content

Connect a front end

A front end needs two things from a session: a view of what it does, and a way to act on it. It acts through your Domain model: it sends commands, and a policy passes them to the session. It reads what the session does from the session, through a route your Worker serves.

The code is from the cloudflare-ai-issues example, which has a web page for an issue.

A session’s client says where it stands and pages through its transcript, from outside the session’s object. The Worker serves both on one route, keyed like the session, by its issue:

src/Worker.ts
if (area === "sessions") {
// A session's key is its issue. The page asks again for what came after the item it last saw.
const session = triage.get(number);
const after = Number(url.searchParams.get("after") ?? 0);
const read: SessionRead = {
...(yield* session.status),
...(yield* session.history({ after, take: 100 })),
};
return yield* HttpServerResponse.json(read);
}

What it answers is one Schema, which the page decodes with:

src/SessionRead.ts
import { SessionPage, SessionState } from "@alchemy.run/ai/Session";
import * as Schema from "effect/Schema";
/**
* What the page reads of one issue's session: where it stands, and the
* transcript items it stored after the one the page last saw.
*/
export const SessionRead = Schema.Struct({ ...SessionState.fields, ...SessionPage.fields });
export type SessionRead = typeof SessionRead.Type;

The Schemas of a session (SessionState, SessionPage, SessionEntry) are in @alchemy.run/ai/Session, which imports only effect, so a browser can bundle them. The page asks again every second with the seq of the last item it has, and gets only what is new. A session’s live events stream stays in its object: to push instead of poll, see serving a session over RPC.

The Api lists the commands a page may send, and serves every view of the board.

src/Board/WebApi.api.ts
import * as Domain from "@alchemy.run/domain";
import { Board } from "./Board.model.ts";
/**
* What the web app may do and read: report an issue, reply on one, and read
* every view. Labeling is left out: only a session sends it.
*/
export class WebApi extends Domain.Api("WebApi", {
model: Board,
commands: ["ReportIssue", "CommentOnIssue"],
}) {}

A page does not call the session. It sends a command, and the model’s policy passes it on, as in Processes and Domain models. Here a reply on an issue is CommentOnIssue, and the policy tells the issue’s session. A session that is working queues it.

The page’s sidebar needs every issue at once. That is one more view, kept under a single key:

src/Board/IssueList.view.ts
import * as Domain from "@alchemy.run/domain";
import { pipe } from "effect/Function";
import * as Optic from "effect/Optic";
import * as Schema from "effect/Schema";
import { Issue } from "./Issue.aggregate.ts";
import { IssueId } from "./Issue.id.ts";
import { Label } from "./LabelIssue.command.ts";
/** The one key the list is kept under. */
export const ALL = "all";
const Listed = Schema.Struct({
title: Schema.String,
label: Schema.NullOr(Label),
replies: Schema.Int,
});
const State = Schema.Struct({
/** Newest first. */
order: Schema.Array(IssueId),
issues: Schema.Record(IssueId, Listed),
});
// Optics into the list. One that focuses on an issue leaves the list as it
// is when the issue is not in it, which keeps evolve total.
const list = Optic.id<typeof State.Type>();
const order = list.key("order");
const listed = (id: IssueId) => list.key("issues").optionalKey(id);
const issue = (id: IssueId) => list.key("issues").at(id);
const without = (id: IssueId) => (ids: ReadonlyArray<IssueId>) => ids.filter((each) => each !== id);
/**
* Every issue of the board, newest first: what the page's sidebar shows. It
* is one entry, which suits a board of a few hundred issues.
*/
export class IssueList extends Domain.View("IssueList", {
from: [Issue],
key: Schema.String,
keyOf: {
IssueReported: () => ALL,
IssueLabeled: () => ALL,
IssueCommented: () => ALL,
},
state: State,
initial: { order: [], issues: {} },
evolve: {
IssueReported: (state, event, { source }) =>
pipe(
state,
order.modify((ids) => [source.id, ...without(source.id)(ids)]),
listed(source.id).modify(() => ({ title: event.title, label: null, replies: 0 })),
),
IssueLabeled: (state, event, { source }) =>
issue(source.id)
.key("label")
.modify(() => event.label)(state),
IssueCommented: (state, _, { source }) =>
issue(source.id)
.key("replies")
.modify((replies) => replies + 1)(state),
},
}) {}

Views are stored, so the list is still there after a refresh or a deploy, and a session keeps its own transcript.

DomainFoldkit.make gives a Command for each command of the Api, and watch and events for each view and stream. The session is one more Subscription: Sessions is a service the page reads it through, a request to /sessions/<issue> in a browser, and the Subscription asks it every second for the open issue. Opening another issue changes what both follow.

The page never waits for the board before it shows something. It keeps what it has read of every issue it opened, so going back to one is instant. A new issue or a reply is put in pending and shown at once, then dropped when the board’s own copy arrives, or taken back when the board refuses it:

web/src/Board.ts
import { QueuedMessage, SessionEntry, SessionStatus } from "@alchemy.run/ai/Session";
import type * as Domain from "@alchemy.run/domain";
import * as DomainFoldkit from "@alchemy.run/domain/Foldkit";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { Command, Subscription, type Update } from "foldkit";
import { defineMessageUnion } from "foldkit/message";
import { modifyFields } from "foldkit/struct";
import { IssueId } from "../../src/Board/Issue.id.ts";
import { ALL } from "../../src/Board/IssueList.view.ts";
import { Label } from "../../src/Board/LabelIssue.command.ts";
import { replied } from "../../src/Board/Said.ts";
import { WebApi } from "../../src/Board/WebApi.api.ts";
import type { SessionRead } from "../../src/SessionRead.ts";
import { issueIn, urlOf } from "./Location.ts";
export type Board = Domain.Api.ClientKey<"WebApi">;
/** One Command per command of the Api, and a read namespace per view and stream. */
export const BoardClient = DomainFoldkit.make(WebApi);
/**
* How the page reads an issue's session: where it stands, and the transcript
* items after `after`. In a browser it is a request to `/sessions/<issue>`;
* a test gives the session itself.
*/
export class Sessions extends Context.Service<
Sessions,
{ readonly read: (issueId: IssueId, after: number) => Effect.Effect<SessionRead, unknown> }
>()("Sessions") {}
/** How often the open issue's session is read. */
const POLL = "1 second";
// MODEL
/** One issue as the sidebar lists it. */
export const Listed = Schema.Struct({
issueId: IssueId,
title: Schema.String,
label: Schema.NullOr(Label),
replies: Schema.Number,
working: Schema.Boolean,
});
export type Listed = typeof Listed.Type;
export const Flags = Schema.Struct({
/** The issue the address names, if it names one. */
issueId: Schema.Option(IssueId),
page: Schema.String,
/** The list as the last visit left it, shown until the board answers. */
issues: Schema.Array(Listed),
});
export type Flags = typeof Flags.Type;
/** What the page knows of one issue. It is kept when another is opened, so coming back is instant. */
export const Thread = Schema.Struct({
/** The issue itself. Known at once for one this page reported or lists. */
detail: Schema.Option(
Schema.Struct({ title: Schema.String, body: Schema.String, label: Schema.NullOr(Label) }),
),
/** Whether its agent is working, and what is queued for it. */
status: SessionStatus,
queued: Schema.Array(QueuedMessage),
/** The agent's transcript so far, and where to resume reading it. */
items: Schema.Array(SessionEntry),
cursor: Schema.Option(Schema.Number),
/** The transcript has been read up to now: what arrives next is live. */
caughtUp: Schema.Boolean,
});
export type Thread = typeof Thread.Type;
const unread: Thread = {
detail: Option.none(),
status: "idle",
queued: [],
items: [],
cursor: Option.none(),
caughtUp: false,
};
/**
* Something the person did that the board has not shown back yet. The page
* shows it at once, and drops it when the board's own copy arrives, or says
* so when the board refuses it.
*/
export const Pending = Schema.Struct({
commandId: Schema.String,
issueId: IssueId,
kind: Schema.Literals(["issue", "reply"]),
/** A reply's text. */
text: Schema.String,
});
export type Pending = typeof Pending.Type;
export const Model = Schema.Struct({
commandIds: DomainFoldkit.CommandIds,
/** Every issue of the board, newest first. */
issues: Schema.Array(Listed),
listed: Schema.Boolean,
/** The issue that is open. None shows the form for a new one. */
selected: Schema.Option(IssueId),
/** The new issue being written. */
title: Schema.String,
body: Schema.String,
/** The reply being written. */
reply: Schema.String,
/** Every issue this page has opened. */
threads: Schema.Record(IssueId, Thread),
pending: Schema.Array(Pending),
error: Schema.Option(Schema.String),
});
export type Model = typeof Model.Type;
/**
* The open issue's thread. While something this page sent is on its way, its
* agent is about to work, whatever the board last said.
*/
export const threadOf = (model: Model): Thread =>
Option.match(model.selected, {
onNone: () => unread,
onSome: (issueId) => {
const known = model.threads[issueId] ?? unread;
return model.pending.some((pending) => pending.issueId === issueId)
? { ...known, status: "working" }
: known;
},
});
/** The sidebar: the board's list, with what this page reported ahead of it. */
export const listOf = (model: Model): ReadonlyArray<Listed & { readonly sending: boolean }> => {
const known = new Set(model.issues.map((issue) => issue.issueId));
const ahead = model.pending.flatMap((pending) =>
pending.kind === "issue" && !known.has(pending.issueId)
? [
{
issueId: pending.issueId,
title: Option.match(model.threads[pending.issueId]?.detail ?? Option.none(), {
onNone: () => "",
onSome: (detail) => detail.title,
}),
label: null,
replies: 0,
working: true,
sending: true,
},
]
: [],
);
return [
...ahead,
...model.issues.map((issue) => ({
...issue,
// The page knows its own issue's agent is at work before the list says so.
working:
issue.working ||
model.threads[issue.issueId]?.status === "working" ||
model.pending.some((pending) => pending.issueId === issue.issueId),
sending: false,
})),
];
};
/** The replies to the open issue that its transcript does not show yet. */
export const sendingOf = (model: Model): ReadonlyArray<Pending> => {
const thread = threadOf(model);
const shown = [
...thread.queued.map((message) => message.text),
...thread.items.flatMap(({ item }) => (item.type === "user" ? [item.text] : [])),
];
return model.pending.filter(
(pending) =>
pending.kind === "reply" &&
Option.contains(model.selected, pending.issueId) &&
!shown.includes(replied(pending.text)),
);
};
// MESSAGE
export const Message = defineMessageUnion({
ClickedNewIssue: {},
ClickedIssue: { issueId: IssueId },
/** The browser's back or forward button moved to another address. */
ChangedAddress: { issueId: Schema.Option(IssueId) },
ChangedTitle: { text: Schema.String },
ChangedBody: { text: Schema.String },
ChangedReply: { text: Schema.String },
SubmittedIssue: {},
SubmittedReply: {},
CompletedShowAddress: {},
CompletedRemember: {},
ReceivedBoardResult: { result: BoardClient.Message },
ReceivedIssues: { issues: Schema.Array(Listed) },
ReceivedIssue: { issueId: IssueId, detail: Thread.fields.detail },
ReceivedStatus: { issueId: IssueId, status: SessionStatus, queued: Schema.Array(QueuedMessage) },
ReceivedItems: { issueId: IssueId, entries: Schema.Array(SessionEntry), cursor: Schema.Number },
CaughtUpTranscript: { issueId: IssueId, cursor: Schema.Number },
FailedRead: { reason: Schema.String },
});
export type Message = typeof Message.Type;
// COMMAND
/** Put the open issue in the address bar, so a refresh or a shared link opens it. */
export const ShowAddress = Command.define("ShowAddress", {
args: { issueId: Schema.Option(IssueId) },
messages: [Message.CompletedShowAddress],
execute: ({ issueId }) =>
Effect.sync(() => {
if (typeof history !== "undefined") {
history.pushState(null, "", urlOf(location.href, issueId));
}
return Message.CompletedShowAddress();
}),
});
/** Keep the list for the next visit, so it is on screen before the board answers. */
export const Remember = Command.define("Remember", {
args: { issues: Schema.Array(Listed) },
messages: [Message.CompletedRemember],
execute: ({ issues }) =>
Effect.sync(() => {
if (typeof localStorage !== "undefined") {
localStorage.setItem(REMEMBERED, JSON.stringify(issues.slice(0, 100)));
}
return Message.CompletedRemember();
}),
});
export const REMEMBERED = "board:issues";
// UPDATE
type Return = Update.Return<Model, Message, Board>;
/** Change what the page knows of one issue. */
const thread = (model: Model, issueId: IssueId, change: (thread: Thread) => Thread): Model =>
modifyFields(model, {
threads: (threads) => ({ ...threads, [issueId]: change(threads[issueId] ?? unread) }),
});
/**
* Open an issue, or none. Nothing is waited for: an issue this page has open
* already is shown as it was left, and one it only lists shows its title.
*/
const show = (model: Model, selected: Option.Option<IssueId>): Model =>
Option.match(selected, {
onNone: () => modifyFields(model, { selected: () => selected, error: () => Option.none() }),
onSome: (issueId) => {
const listed = model.issues.find((issue) => issue.issueId === issueId);
const opened = thread(model, issueId, (known) =>
Option.isSome(known.detail) || listed === undefined
? known
: {
...known,
detail: Option.some({ title: listed.title, body: "", label: listed.label }),
status: listed.working ? "working" : known.status,
},
);
return modifyFields(opened, {
selected: () => selected,
reply: () => "",
error: () => Option.none(),
});
},
});
/** Send one command of the Api, named so that a retry is not run twice. */
const send = (
model: Model,
command: (commandId: string) => Command.Command<typeof BoardClient.Message.Type, never, Board>,
): Return & { readonly commandId: string } => {
const { commandId, commandIds } = DomainFoldkit.next(model.commandIds);
return {
commandId,
model: modifyFields(model, { commandIds: () => commandIds, error: () => Option.none() }),
commands: [
Command.mapMessage(command(commandId), (result) => Message.ReceivedBoardResult({ result })),
],
};
};
/** The board refused, or never answered: take back what the page showed ahead of it. */
const undo = (model: Model, commandId: string, reason: string): Model => {
const refused = model.pending.find((pending) => pending.commandId === commandId);
const rest = modifyFields(model, {
pending: (pending) => pending.filter((each) => each.commandId !== commandId),
error: () => Option.some(reason),
});
if (refused === undefined) return rest;
if (refused.kind === "reply") {
// The words go back in the box, unless the person has started another.
return modifyFields(rest, { reply: (reply) => (reply === "" ? refused.text : reply) });
}
const written = Option.getOrUndefined(rest.threads[refused.issueId]?.detail ?? Option.none());
const { [refused.issueId]: _dropped, ...threads } = rest.threads;
return modifyFields(rest, {
threads: () => threads,
selected: (selected) => (Option.contains(selected, refused.issueId) ? Option.none() : selected),
title: (title) => (title === "" ? (written?.title ?? "") : title),
body: (body) => (body === "" ? (written?.body ?? "") : body),
});
};
export const update = (model: Model, message: Message) =>
Message.match<Return>(message, {
ClickedNewIssue: () => ({
model: show(model, Option.none()),
commands: [ShowAddress({ issueId: Option.none() })],
}),
ClickedIssue: ({ issueId }) => ({
model: show(model, Option.some(issueId)),
commands: [ShowAddress({ issueId: Option.some(issueId) })],
}),
ChangedAddress: ({ issueId }) => ({ model: show(model, issueId) }),
ChangedTitle: ({ text }) => ({ model: modifyFields(model, { title: () => text }) }),
ChangedBody: ({ text }) => ({ model: modifyFields(model, { body: () => text }) }),
ChangedReply: ({ text }) => ({ model: modifyFields(model, { reply: () => text }) }),
// Reporting the issue is what starts its agent: the board's policy does that.
SubmittedIssue: () => {
const title = model.title.trim();
const body = model.body.trim();
if (title === "") return { model };
// The page names the issue, so it can show it before the board answers.
const issueId = IssueId.make(
`${model.commandIds.session}-${model.commandIds.sent}`.replace(/[^\w-]/g, "-"),
);
const sent = send(model, (commandId) =>
BoardClient.ReportIssue({ input: { issueId, title, body }, commandId }),
);
// Shown at once: the issue as written, its agent starting, and a place in the list.
const written = thread(sent.model, issueId, () => ({
...unread,
detail: Option.some({ title, body, label: null }),
caughtUp: true,
}));
return {
model: modifyFields(written, {
selected: () => Option.some(issueId),
title: () => "",
body: () => "",
reply: () => "",
pending: (pending) => [
...pending,
{ commandId: sent.commandId, issueId, kind: "issue" as const, text: "" },
],
}),
commands: [...(sent.commands ?? []), ShowAddress({ issueId: Option.some(issueId) })],
};
},
// A reply is passed to the agent by the same policy. A working agent queues it.
SubmittedReply: () =>
Option.match(model.selected, {
onNone: (): Return => ({ model }),
onSome: (issueId) => {
const text = model.reply.trim();
if (text === "") return { model };
const sent = send(model, (commandId) =>
BoardClient.CommentOnIssue({
input: { issueId, commentId: commandId, body: text },
commandId,
}),
);
return {
// Shown at once, with the agent taking it up.
model: modifyFields(sent.model, {
reply: () => "",
pending: (pending) => [
...pending,
{ commandId: sent.commandId, issueId, kind: "reply" as const, text },
],
}),
commands: sent.commands,
};
},
}),
CompletedShowAddress: () => ({ model }),
CompletedRemember: () => ({ model }),
ReceivedBoardResult: ({ result }) => ({
model:
result._tag === "FailedReportIssue" || result._tag === "FailedCommentOnIssue"
? undo(
model,
result.commandId,
result.failure._tag === "Rejected"
? result.failure.rejection._tag
: "The board did not answer. Your words are back in the box.",
)
: model,
}),
ReceivedIssues: ({ issues }) => ({
model: modifyFields(model, { issues: () => issues, listed: () => true }),
commands: [Remember({ issues })],
}),
ReceivedIssue: ({ issueId, detail }) => ({
// The board's copy replaces the page's, once it has one.
model: Option.isNone(detail)
? model
: thread(model, issueId, (known) => ({ ...known, detail })),
}),
ReceivedStatus: ({ issueId, status, queued }) => ({
model: thread(model, issueId, (known) => ({
...known,
queued,
status,
})),
}),
ReceivedItems: ({ issueId, entries, cursor }) => {
const read = thread(model, issueId, (known) => ({
...known,
items: [
...known.items,
...entries.filter((entry) => !known.items.some((item) => item.seq === entry.seq)),
],
cursor: Option.some(cursor),
}));
// The agent has it: the page's own copy of the reply, or of the issue, is done.
const texts = entries.flatMap(({ item }) => (item.type === "user" ? [item.text] : []));
const arrived = read.pending.find(
(pending) =>
pending.issueId === issueId &&
(pending.kind === "issue" ? texts.length > 0 : texts.includes(replied(pending.text))),
);
return {
model:
arrived === undefined
? read
: modifyFields(read, {
pending: (pending) => pending.filter((each) => each !== arrived),
}),
};
},
CaughtUpTranscript: ({ issueId, cursor }) => ({
model: thread(model, issueId, (known) => ({
...known,
cursor: Option.some(cursor),
caughtUp: true,
})),
}),
FailedRead: ({ reason }) => ({
model: modifyFields(model, { error: () => Option.some(reason) }),
}),
});
// INIT
export const init = (flags: Flags): Return => ({
model: show(
Model.make({
commandIds: { session: flags.page, sent: 0 },
issues: flags.issues,
listed: false,
selected: Option.none(),
title: "",
body: "",
reply: "",
threads: {},
pending: [],
error: Option.none(),
}),
flags.issueId,
),
});
// SUBSCRIPTION
const open = (model: Model) => Option.getOrElse(model.selected, () => IssueId.make(""));
const isOpen = (model: Model) => Option.isSome(model.selected);
const failed = (error: { readonly _tag: string }): Message =>
Message.FailedRead({ reason: error._tag });
const defect = (): Message => Message.FailedRead({ reason: "The board could not be read" });
export const subscriptions = Subscription.make<Model, Message, Board | Sessions>()((entry) => ({
// Back and forward open the issue their address names.
address: entry(
{},
{
modelToDependencies: () => ({}),
dependenciesToStream: () =>
typeof window === "undefined"
? Stream.empty
: Stream.fromEventListener(window, "popstate").pipe(
Stream.map(() => Message.ChangedAddress({ issueId: issueIn(location.href) })),
),
},
),
issues: BoardClient.IssueList.watch({
key: () => ALL,
toMessage: ({ state }): Message =>
Message.ReceivedIssues({
issues: Option.match(state, {
onNone: () => [],
onSome: (list) =>
list.order.flatMap((issueId) => {
const issue = list.issues[issueId];
return issue === undefined
? []
: // Whether an agent is working is its session's to say, not the board's.
[{ issueId, ...issue, working: false }];
}),
}),
}),
onFailure: failed,
onDefect: defect,
}),
issue: BoardClient.IssueDetail.watch({
key: open,
isEnabled: isOpen,
toMessage: ({ state }, issueId): Message =>
Message.ReceivedIssue({
issueId,
detail: Option.map(state, ({ title, body, label }) => ({ title, body, label })),
}),
onFailure: failed,
onDefect: defect,
}),
// The open issue's session, read again every second: where it stands,
// then each transcript item the page does not have yet.
session: entry(
{ issueId: IssueId, isEnabled: Schema.Boolean },
{
modelToDependencies: (model) => ({ issueId: open(model), isEnabled: isOpen(model) }),
dependenciesToStream: ({ issueId, isEnabled }) => {
if (!isEnabled) return Stream.empty;
// The last item this stream handed over: the next read asks for what came after.
let after = 0;
const read = Effect.gen(function* () {
const sessions = yield* Sessions;
const { status, queued, items, next } = yield* sessions.read(issueId, after);
after = items.at(-1)?.seq ?? after;
return [
Message.ReceivedStatus({ issueId, status, queued }),
...(items.length === 0
? []
: [Message.ReceivedItems({ issueId, entries: items, cursor: after })]),
// The last page: what arrives from now on is new.
...(next === undefined ? [Message.CaughtUpTranscript({ issueId, cursor: after })] : []),
];
}).pipe(
// A read that fails is tried again at the next tick.
Effect.catchCause(() => Effect.succeed<ReadonlyArray<Message>>([])),
);
return Stream.fromEffectSchedule(read, Schedule.spaced(POLL)).pipe(
Stream.flatMap((messages) => Stream.fromIterable(messages)),
);
},
},
),
}));

The open issue is kept in the address, so a refresh or a shared link opens it again:

web/src/Location.ts
import * as Option from "effect/Option";
import { IssueId } from "../../src/Board/Issue.id.ts";
/** The issue an address names with `?issue=`, if it names one. */
export const issueIn = (url: string): Option.Option<IssueId> => {
const named = new URL(url).searchParams.get("issue");
return named === null || named === "" ? Option.none() : Option.some(IssueId.make(named));
};
/** The address that opens an issue, or the board with none open. */
export const urlOf = (url: string, issueId: Option.Option<IssueId>): string => {
const parsed = new URL(url);
Option.match(issueId, {
onNone: () => parsed.searchParams.delete("issue"),
onSome: (id) => parsed.searchParams.set("issue", id),
});
return parsed.toString();
};

The client is provided once, on the app’s own origin:

web/src/entry.ts
import * as Domain from "@alchemy.run/domain";
import * as Effect from "effect/Effect";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Socket from "effect/socket/Socket";
import { Runtime } from "foldkit";
import { WebApi } from "../../src/Board/WebApi.api.ts";
import { SessionRead } from "../../src/SessionRead.ts";
import {
Flags,
init,
Listed,
Model,
REMEMBERED,
Sessions,
subscriptions,
update,
} from "./Board.ts";
import { issueIn } from "./Location.ts";
import { view } from "./View.ts";
/**
* The board's Api for the life of the app. Commands go over HTTP. Each live
* read is a WebSocket to the Durable Object that owns what it reads.
*/
const BoardConnection = WebApi.layerClient.pipe(
Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)),
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Socket.layerWebSocketConstructorGlobal)),
);
/** An issue's session, read from the board's Worker on the page's own origin. */
const SessionsOverHttp = Layer.succeed(Sessions, {
read: (issueId, after) =>
Effect.tryPromise(() =>
fetch(`${location.origin}/sessions/${encodeURIComponent(issueId)}?after=${after}`).then(
(response) => response.json(),
),
).pipe(Effect.flatMap(Schema.decodeUnknownEffect(SessionRead))),
});
Runtime.run(
Runtime.makeApplication({
Model,
Flags,
init,
update,
view,
subscriptions,
resources: Layer.mergeAll(BoardConnection, SessionsOverHttp),
container: document.getElementById("root"),
}),
{
flags: Effect.sync(() => ({
// The issue the address names is opened: a refresh or a shared link resumes it.
issueId: issueIn(location.href),
// Short, and names this page's commands and issues: each is unique across reloads.
page: crypto.randomUUID().slice(0, 8),
// The list as the last visit left it, on screen before the board answers.
issues: Option.getOrElse(
Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Array(Listed)))(
localStorage.getItem(REMEMBERED) ?? "[]",
),
() => [],
),
})),
},
);

web/src/View.ts draws it: a list of issues, and the open one as a thread, with each tool call joined to its result.

The page’s update is tested with Foldkit stories. To test the page and the board together, run the page’s own init, update, Commands and Subscriptions against the board in memory:

test/App.ts
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import type { WebApi } from "../src/Board/WebApi.api.ts";
import {
type Flags,
init,
type Message,
type Model,
type Sessions,
subscriptions,
update,
} from "../web/src/Board.ts";
type Client = (typeof WebApi)["Client"]["Identifier"] | Sessions;
/**
* Run the web page without a browser: its own `init`, `update`, Commands and
* Subscriptions, against whatever board the `WebApi` client reaches and
* whatever sessions `Sessions` reads. Only the view is left out. It stops when the scope closes.
*/
export const open = Effect.fn(function* (flags: Flags) {
const started = init(flags);
let current: Model = started.model;
const models = yield* SubscriptionRef.make(current);
const dispatch = (message: Message): Effect.Effect<void, never, Client> =>
Effect.gen(function* () {
const next = update(current, message);
current = next.model;
yield* SubscriptionRef.set(models, current);
// Each Command runs in the background, and its Message is dispatched in turn.
for (const command of next.commands ?? []) {
yield* Effect.forkDetach(Effect.flatMap(command.effect, dispatch));
}
});
// Each Subscription follows its dependencies: when they change (another
// issue is opened), its Stream is restarted, as Foldkit's runtime does.
for (const entry of Object.values(subscriptions)) {
const read = () => entry.modelToDependencies(current) as unknown;
const same = (entry as { keepAliveEquivalence?: (a: unknown, b: unknown) => boolean })
.keepAliveEquivalence;
const key = (dependencies: unknown) => JSON.stringify(dependencies);
const run = entry.dependenciesToStream as unknown as (
dependencies: unknown,
read: () => unknown,
) => Stream.Stream<Message, never, Client>;
const messages: Stream.Stream<Message, never, Client> = SubscriptionRef.changes(models).pipe(
Stream.map(read),
Stream.changesWith((a, b) => (same ? same(a, b) : key(a) === key(b))),
Stream.switchMap((dependencies) => run(dependencies, read)),
);
yield* Effect.forkScoped(Stream.runForEach(messages, dispatch));
}
return {
/** What a click or a keystroke does. */
dispatch,
/** The Model once it satisfies `predicate`. */
until: (predicate: (model: Model) => boolean) =>
SubscriptionRef.changes(models).pipe(
Stream.filter(predicate),
Stream.runHead,
Effect.map(() => current),
Effect.timeout("90 seconds"),
Effect.orDie,
),
};
});

AI.scripted plays Triage in place of a model, and AI.layerInMemory hosts it as the real one is hosted. Sessions reads the session itself, so the page sees a status and a transcript with no network:

test/App.test.ts
const TriagePlayed = AI.scripted(
Triage,
Effect.gen(function* () {
const issues = yield* Issue;
return Effect.fn(function* ({ key, text }: AI.Turn) {
const label = text.includes("question") ? "question" : "bug";
yield* issues.send(new LabelIssue({ issueId: IssueId.make(key), label }));
return `Labeled ${label}.`;
}, Effect.orDie);
}),
);
const BoardInMemory = Board.layer(IssueWorkLive).pipe(
Layer.provideMerge(Domain.InMemory),
Layer.provideMerge(SecureRandom.layerWebCrypto),
);
const TriageInMemory = AI.layerInMemory(TriagePlayed.pipe(Layer.provide(BoardInMemory)));
const Hosted = Layer.mergeAll(BoardInMemory, TriageInMemory).pipe(Layer.provide(TriageInMemory));
/** The page's read of a session, from the session itself instead of over a network. */
const SessionsInProcess = Layer.effect(
Sessions,
Effect.gen(function* () {
const triage = yield* Triage;
return {
read: (issueId, after) =>
Effect.gen(function* () {
const session = triage.get(issueId);
return { ...(yield* session.status), ...(yield* session.history({ after, take: 100 })) };
}).pipe(Effect.provide(RuntimeContext.phantom)),
};
}),
);
/** The page's client, with the board in this process instead of over a network. */
const Live = Layer.mergeAll(WebApi.layerClientInProcess, SessionsInProcess).pipe(
Layer.provideMerge(Hosted),
);

The same runner drives a deployed stack in test/integ.test.ts, with the real agent.

The page is built with Vite and served by its own Worker, which forwards /api and /sessions to the board:

alchemy.run.ts
import * as Boat from "@alchemy.run/boat";
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as DomainCloudflare from "@alchemy.run/domain/Cloudflare";
import * as GitHub from "@alchemy.run/github";
import * as Alchemy from "alchemy";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { Repo } from "./src/Repo.ts";
import Worker from "./src/Worker.ts";
export default Alchemy.Stack(
"CloudflareAiIssues",
{
providers: Layer.mergeAll(
Cloudflare.providers(),
DomainCloudflare.providers(),
Boat.providers(),
GitHub.providers(),
),
state: Alchemy.localState(),
},
Effect.gen(function* () {
const repo = yield* Repo;
const worker = yield* Worker;
// The foldkit app, built with Vite. Its Worker serves the build and
// forwards /api and /sessions to the board, so they share one origin.
const app = yield* Cloudflare.Website.Foldkit("BoardApp", {
rootDir: "web",
main: "src/worker.ts",
env: { BOARD: worker },
assets: { runWorkerFirst: ["/api", "/api/*", "/sessions/*"] },
});
return { url: worker.url, app: app.url, repository: repo.htmlUrl };
}),
);

To push a session’s events to a page as they happen, or to let a page act on a session with no model in between, serve the session over an Effect RPC group of your own. A session’s live events are read where its process’s Layer is built, so this is a Durable Object you write that yields the process. Alchemy AI gives the Schemas, and Alchemy serves the group over a WebSocket from that object.

@alchemy.run/ai/Session has a Schema for everything a session says about itself: SessionEvent, SessionEntry, SessionItem, QueuedMessage, HistoryOptions and SessionPage. Use them as the results of your own procedures:

src/chat/Rpcs.ts
import { HistoryOptions, SessionEvent, SessionPage } from "@alchemy.run/ai/Session";
import * as Rpc from "effect/rpc/Rpc";
import * as RpcGroup from "effect/rpc/RpcGroup";
import * as Schema from "effect/Schema";
/** The session could not do what it was asked. */
export class ChatError extends Schema.TaggedClass<ChatError>()("ChatError", {
message: Schema.String,
}) {}
const Text = { text: Schema.String, requestId: Schema.String };
/** What the front end may ask of one session. */
export class ChatRpcs extends RpcGroup.make(
Rpc.make("send", { payload: Text, error: ChatError }),
Rpc.make("steer", { payload: Text, error: ChatError }),
Rpc.make("withdraw", { payload: { id: Schema.String }, error: ChatError }),
Rpc.make("interrupt", { error: ChatError }),
Rpc.make("events", {
payload: { after: Schema.optional(Schema.Number) },
success: SessionEvent,
error: ChatError,
stream: true,
}),
Rpc.make("history", { payload: HistoryOptions, success: SessionPage, error: ChatError }),
) {}

events is a stream. The interface is yours, so it holds only what this front end may do: leave out interrupt, add a field, or put a middleware on it.

Each procedure calls one method of AI.Session:

src/chat/Handlers.ts
import type * as AI from "@alchemy.run/ai";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { ChatError, ChatRpcs } from "./Rpcs.ts";
const failed = (error: AI.NotStarted | AI.HarnessError) =>
ChatError.make({ message: error._tag === "NotStarted" ? "Not started" : error.message });
/** Each procedure is one method of the session. */
export const ChatHandlers = (session: AI.Session) =>
ChatRpcs.toLayer({
send: ({ text, requestId }) => session.send(text, { requestId }).pipe(Effect.mapError(failed)),
steer: ({ text, requestId }) =>
session.steer(text, { requestId }).pipe(Effect.mapError(failed)),
withdraw: ({ id }) => session.withdraw(id).pipe(Effect.mapError(failed)),
interrupt: () => session.interrupt.pipe(Effect.mapError(failed)),
events: ({ after }) => session.events({ after }).pipe(Stream.mapError(failed)),
history: (options) => session.history(options).pipe(Effect.mapError(failed)),
});

Cloudflare.RpcDurableObject serves a group over HTTP and over a WebSocket. Return the handlers for the session the object holds:

src/Engineers.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import { ChatHandlers } from "./chat/Handlers.ts";
import { ChatRpcs } from "./chat/Rpcs.ts";
import { Engineer } from "./Engineer.process.ts";
import { Live } from "./Layers.ts";
export default class Engineers extends Cloudflare.RpcDurableObject<Engineers>()(
"Engineers",
{ schema: ChatRpcs },
Effect.gen(function* () {
const engineer = yield* Engineer;
const state = yield* Cloudflare.DurableObjectState;
return Effect.sync(() => ChatHandlers(engineer.get(state.id.name ?? "")));
}).pipe(Effect.provide(Live)),
) {}

The object is named after the session’s key, so each session has an object of its own. Live is the Layer from Where sessions run.

The Worker maps a URL to an object and forwards the request. The same route carries plain HTTP calls and the WebSocket upgrade:

src/Api.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import Engineers from "./Engineers.ts";
export default class Api extends Cloudflare.Worker<Api>()(
"Api",
{ main: import.meta.url },
Effect.gen(function* () {
const engineers = yield* Engineers;
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
const id = /^\/sessions\/([\w-]+)$/.exec(new URL(request.url, "http://api").pathname)?.[1];
if (id === undefined) return HttpServerResponse.empty({ status: 404 });
return yield* engineers.fetch(id, request);
}).pipe(Effect.orDie),
};
}),
) {}

Anyone who can open this route can read and steer that session. Check who is asking before you call fetch, or take the id from the signed-in user.

In the browser, RpcWebSocketClient.layer gives a typed client over one WebSocket. follow reads the session’s events and resumes after a reconnect:

web/Client.ts
import type { SessionEvent } from "@alchemy.run/ai/Session";
import * as RpcWebSocketClient from "@alchemy.run/cloudflare/Workers/RpcWebSocketClient";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as RpcClient from "effect/rpc/RpcClient";
import type { RpcClientError } from "effect/rpc/RpcClientError";
import * as Socket from "effect/socket/Socket";
import * as Stream from "effect/Stream";
import { ChatRpcs, type ChatError } from "./Rpcs.ts";
/** The typed client of one session. */
export class Chat extends Context.Service<
Chat,
RpcClient.FromGroup<typeof ChatRpcs, RpcClientError>
>()("Chat") {}
/** One WebSocket to the session's object, open for as long as the Layer is. */
export const ChatLive = (url: string) =>
RpcWebSocketClient.layer(Chat, ChatRpcs, url).pipe(
Layer.provide(Socket.layerWebSocketConstructorGlobal),
);
/**
* The session's events for as long as they are read. When the connection
* drops it asks again from the last item it delivered.
*/
export const follow = (options?: {
readonly after?: number;
}): Stream.Stream<SessionEvent, ChatError, Chat> =>
Stream.suspend(() => {
let after = options?.after;
const read = (): Stream.Stream<SessionEvent, ChatError, Chat> =>
Stream.unwrap(Effect.map(Chat, (chat) => chat.events({ after }))).pipe(
Stream.tap((event) =>
Effect.sync(() => {
if (event.type === "item") after = event.seq;
}),
),
Stream.catchTag("RpcClientError", () =>
Stream.flatMap(Stream.fromEffect(Effect.sleep("1 second")), read),
),
);
return read();
});

The first event is the status: idle or working, and the messages that are queued. Then come the stored items, then each new one as it happens. A change of status follows the items stored with it, so idle arrives after the answer.

The stream is the whole picture. A page that folds these events knows the transcript, whether the session is working and what is queued, with no other call.

An idle object is put to sleep with its sockets open, and wakes when the session is sent something. Each item has a seq, so follow asks again from the last one it delivered and nothing is missed or repeated.

The client has the procedures you declared:

web/act.ts
import * as Effect from "effect/Effect";
import { Chat } from "./Client.ts";
export const act = Effect.gen(function* () {
const chat = yield* Chat;
yield* chat.send({ text: "Rename the config flag.", requestId: "m-1" });
yield* chat.steer({ text: "Only in src.", requestId: "m-2" });
yield* chat.interrupt();
});

A requestId makes a message exactly-once, so a retry after a lost answer is safe.