Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions apps/site-e2e/tests/features/todo/__fixtures__/mcp.fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Config, ConfigProvider, Effect, Layer, Option } from 'effect'
import * as McpClient from 'effect/ai/McpClient'
import * as McpProtocol from 'effect/ai/McpProtocol'
import { FetchHttpClient } from 'effect/http'
import * as S from 'effect/Schema'

const siteUrl = Effect.orDie(
Config.String('SITE_URL').pipe(
Config.withDefault('http://localhost:1337'),
(config) => config.parse(ConfigProvider.fromEnv()),
),
)

export const McpClientLive = Layer.unwrap(
Effect.map(siteUrl, (origin) =>
McpClient.layerHttp({
name: 'todo-agent',
version: '1.0.0',
protocol: McpProtocol.v2026_07_28,
url: `${origin}/mcp`,
})),
).pipe(Layer.provide(FetchHttpClient.layer), Layer.orDie)

const TodoShape = S.Struct({
id: S.String,
text: S.String,
done: S.Boolean,
position: S.Int,
version: S.Int,
createdAt: S.Int,
})

const AddedShape = S.Struct({ todo: TodoShape })

const ListedShape = S.Array(TodoShape)

export interface ToolOutcome {
readonly tools: ReadonlyArray<string>
readonly added: S.Schema.Type<typeof AddedShape>
readonly listed: S.Schema.Type<typeof ListedShape>
}

export const credential = (): string => `${crypto.randomUUID().replaceAll('-', '')}${crypto.randomUUID().slice(0, 11)}`

const callTool = (name: string, args: { readonly credential: string; readonly text?: string }) =>
Effect.gen(function*() {
const client = yield* McpClient.McpClient
const tools = yield* client.listTools()
const tool = Option.fromNullishOr(tools.find((candidate) => candidate.name === name))
return yield* Option.match(tool, {
onNone: () => Effect.die(new Error(`the server does not offer ${name}`)),
onSome: (found) => client.callTool({ tool: found, arguments: args }),
})
})

export const throughTheTools: Effect.Effect<ToolOutcome, never, McpClient.McpClient> = Effect.gen(function*() {
const client = yield* McpClient.McpClient
const tools = yield* client.listTools()
const key = credential()
const added = yield* callTool('todo_add', { credential: key, text: 'buy milk' })
const listed = yield* callTool('todo_list', { credential: key })
return {
tools: tools.map((tool) => tool.name),
added: yield* S.decodeUnknownEffect(AddedShape)(added.structuredContent),
listed: yield* S.decodeUnknownEffect(ListedShape)(listed.structuredContent),
}
}).pipe(Effect.orDie)
122 changes: 122 additions & 0 deletions apps/site-e2e/tests/features/todo/__fixtures__/todo.fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { Config, ConfigProvider, Effect } from 'effect'
import type { Page } from 'playwright'

import { Chromium } from '../../../__fixtures__/browser.fixture'

const siteUrl = Effect.orDie(
Config.String('SITE_URL').pipe(
Config.withDefault('http://localhost:1337'),
(config) => config.parse(ConfigProvider.fromEnv()),
),
)

export interface TodoVisit {
readonly todos: ReadonlyArray<string>
readonly notice: string
}

export interface TwoPersons {
readonly first: ReadonlyArray<string>
readonly second: ReadonlyArray<string>
}

const composerReady = (): boolean => {
const button = document.querySelector('button.todo__add')
return button !== null && !button.hasAttribute('disabled')
}

const todoLines = (page: Page): Promise<ReadonlyArray<string>> =>
page.locator('ol.todo__list li .todo__text').allTextContents()

const noticeOf = (page: Page): Promise<string> => page.locator('.todo__notice').textContent().then((text) => text ?? '')

const rpcAnswered = (page: Page, procedure: string) =>
page.waitForResponse((response) =>
response.url().endsWith('/api/rpc') && response.request().postData()?.includes(`"tag":"${procedure}"`) === true
)

const visitOf = (page: Page) =>
Effect.gen(function*() {
const todos = yield* Effect.promise(() => todoLines(page))
const notice = yield* Effect.promise(() => noticeOf(page))
return { todos, notice } satisfies TodoVisit
})

const opened = async (page: Page, origin: string): Promise<void> => {
await page.goto(`${origin}/todo`)
await page.waitForFunction(composerReady)
}

const addTodo = async (page: Page, text: string): Promise<void> => {
const answered = rpcAnswered(page, 'todo_add')
await page.locator('#todo-new').fill(text)
await page.getByRole('button', { name: 'Add' }).click()
await answered
}

const inFreshContext = <A, R = never>(
use: (page: Page, origin: string) => Effect.Effect<A, never, R>,
): Effect.Effect<A, never, Chromium | R> =>
Effect.gen(function*() {
const origin = yield* siteUrl
const browser = yield* Chromium
return yield* Effect.acquireUseRelease(
Effect.promise(() => browser.newContext()),
(context) => Effect.flatMap(Effect.promise(() => context.newPage()), (page) => use(page, origin)),
(context) => Effect.promise(() => context.close()),
)
})

export const addedAndReloaded = (text: string): Effect.Effect<TodoVisit, never, Chromium> =>
inFreshContext((page, origin) =>
Effect.gen(function*() {
yield* Effect.promise(() => opened(page, origin))
yield* Effect.promise(() => addTodo(page, text))
yield* Effect.promise(() => page.reload())
yield* Effect.promise(() => page.waitForFunction(composerReady))
yield* Effect.promise(() => page.waitForFunction(() => document.querySelectorAll('ol.todo__list li').length > 0))
return yield* visitOf(page)
})
)

export const workedThroughTheList: Effect.Effect<TodoVisit, never, Chromium> = inFreshContext((page, origin) =>
Effect.gen(function*() {
yield* Effect.promise(() => opened(page, origin))
yield* Effect.promise(async () => {
await addTodo(page, 'first task')
await addTodo(page, 'second task')

const completed = rpcAnswered(page, 'todo_complete')
await page.getByRole('button', { name: 'Mark first task done' }).click()
await completed

const renamed = rpcAnswered(page, 'todo_rename')
await page.getByRole('button', { name: 'Rename second task' }).click()
await page.getByLabel('Rename second task').fill('renamed task')
await page.getByLabel('Rename second task').press('Enter')
await renamed

const moved = rpcAnswered(page, 'todo_reorder')
await page.getByRole('button', { name: 'Move renamed task up' }).click()
await moved

const removed = rpcAnswered(page, 'todo_remove')
await page.getByRole('button', { name: 'Delete first task' }).click()
await removed
})
return yield* visitOf(page)
})
)

export const twoPersonsLists: Effect.Effect<TwoPersons, never, Chromium> = inFreshContext((firstPage, origin) =>
inFreshContext((secondPage) =>
Effect.gen(function*() {
yield* Effect.promise(() => opened(firstPage, origin))
yield* Effect.promise(() => addTodo(firstPage, 'a private task'))
yield* Effect.promise(() => opened(secondPage, origin))
const first = yield* Effect.promise(() => todoLines(firstPage))
const second = yield* Effect.promise(() => todoLines(secondPage))
return { first, second } satisfies TwoPersons
})
)
)
55 changes: 55 additions & 0 deletions apps/site-e2e/tests/features/todo/mcp.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Gherkin, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec'

import { McpClientLive, throughTheTools } from './__fixtures__/mcp.fixture'

const Feature = makeFeature({ it })

const MCP_TIMEOUT_MS = 60_000

Feature('Working with the todos over the MCP surface', { timeout: MCP_TIMEOUT_MS })
.withLayer(McpClientLive)
.live('the running Worker serves the todo tools it derives from the todo contract')
.body(({ scenario }) => {
scenario(
'An agent lists the todo tools and adds a todo it can then list',
Gherkin.Do.pipe(
When('the agent calls the todo tools')('outcome', () => throughTheTools),
Then('the todo tools are offered and the added todo comes back from the list')((s, expect) =>
expect({
tools: s.outcome.tools,
added: s.outcome.added,
listed: s.outcome.listed,
}).toEqual({
tools: [
'todo_list',
'todo_add',
'todo_complete',
'todo_rename',
'todo_reorder',
'todo_remove',
],
added: {
todo: {
id: expect.any(String),
text: 'buy milk',
done: false,
position: 0,
version: 1,
createdAt: expect.any(Number),
},
},
listed: [
{
id: expect.any(String),
text: 'buy milk',
done: false,
position: 0,
version: 1,
createdAt: expect.any(Number),
},
],
})
),
),
)
})
43 changes: 43 additions & 0 deletions apps/site-e2e/tests/features/todo/todo.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Gherkin, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec'

import { ChromiumLive } from '../../__fixtures__/browser.fixture'
import { addedAndReloaded, twoPersonsLists, workedThroughTheList } from './__fixtures__/todo.fixture'

const Feature = makeFeature({ it })

const CHROMIUM_TIMEOUT_MS = 60_000

Feature('Keeping a list of todos in the browser', { timeout: CHROMIUM_TIMEOUT_MS })
.withLayer(ChromiumLive)
.live('a real Chromium drives the todo page the running Worker serves, over its own local D1 database')
.body(({ scenario }) => {
scenario(
'A visitor adds a todo and finds it again after a reload',
Gherkin.Do.pipe(
When('a visitor adds a todo and reloads the page')('visit', () => addedAndReloaded('buy milk')),
Then('the todo is still on the list, with no notice')((s, expect) =>
expect(s.visit).toEqual({ todos: ['buy milk'], notice: '' })
),
),
)

scenario(
'A visitor completes, renames, moves and deletes todos',
Gherkin.Do.pipe(
When('a visitor works through the list')('visit', () => workedThroughTheList),
Then('the renamed todo is first and the completed one is gone')((s, expect) =>
expect(s.visit).toEqual({ todos: ['renamed task'], notice: '' })
),
),
)

scenario(
"One person never sees another person's todos",
Gherkin.Do.pipe(
When('two people open their own lists')('lists', () => twoPersonsLists),
Then('the first person sees their todo and the second sees none')((s, expect) =>
expect(s.lists).toEqual({ first: ['a private task'], second: [] })
),
),
)
})
8 changes: 7 additions & 1 deletion apps/site/alchemy.run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ const productionDomain = (stage: string): { readonly domain?: string } => {

export const Database = Cloudflare.D1.Database('Database', { migrations: 'src/features/guestbook/migrations' })

export const TodoDatabase = Cloudflare.D1.Database('TodoDatabase', { migrations: 'src/features/todo/migrations' })

export const Site = Cloudflare.Website.Vite(
'Site',
Effect.gen(function*() {
Expand All @@ -25,7 +27,11 @@ export const Site = Cloudflare.Website.Vite(
compatibility: { date: siteWorker.compatibilityDate, flags: [...siteWorker.compatibilityFlags] },
assets: { runWorkerFirst: ['/app', '/app/*'] },
dev: { port: 1337, strictPort: true },
env: { DB: yield* Database },
env: {
DB: yield* Database,
TODO_DB: yield* TodoDatabase,
OTEL_EXPORTER_OTLP_ENDPOINT: process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? '',
},
...productionDomain(stage),
}
}),
Expand Down
29 changes: 29 additions & 0 deletions apps/site/fakes/clock.fake.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as Clock from 'effect/Clock'
import * as Duration from 'effect/Duration'
import * as Effect from 'effect/Effect'

export interface FakeClock extends Clock.Clock {
readonly set: (millis: number) => void
readonly advance: (millis: number) => void
}

const NANOS_PER_MILLI = 1_000_000n

export const make = (start: number = 1_700_000_000_000): FakeClock => {
let now = start
return {
currentTimeMillisUnsafe: () => now,
currentTimeMillis: Effect.sync(() => now),
currentTimeNanosUnsafe: () => BigInt(now) * NANOS_PER_MILLI,
currentTimeNanos: Effect.sync(() => BigInt(now) * NANOS_PER_MILLI),
monotonicTimeNanosUnsafe: () => BigInt(now) * NANOS_PER_MILLI,
monotonicTimeNanos: Effect.sync(() => BigInt(now) * NANOS_PER_MILLI),
sleep: (duration: Duration.Duration) => Effect.sleep(duration),
set: (millis: number) => {
now = millis
},
advance: (millis: number) => {
now = now + millis
},
}
}
Loading
Loading