opencode/packages/server/test/event-feed.test.ts
Sebastian d580636cd4
feat(server): experimental spaces (#63998)
Co-authored-by: kommander <335157+kommander@users.noreply.github.com>
2026-11-26 16:45:28 +01:00

230 lines
8.6 KiB
TypeScript

import { describe, expect, test } from "bun:test"
import { Agent } from "@opencode/core/agent"
import { Bus } from "@opencode/core/bus"
import { Credential } from "@opencode/schema/credential"
import { Event } from "@opencode/schema/event"
import { IntegrationID } from "@opencode/schema/integration-id"
import { Deferred, Effect, Exit, Fiber, Option, Schema, Stream } from "effect"
import { it } from "../../core/test/lib/effect"
import { EventFeed } from "../src/event-feed"
const Internal = Bus.ephemeral({ type: "test.internal", schema: { value: Schema.String } })
const event = (id: string): Event.Payload<typeof Agent.Event.Updated> => ({
id: Event.ID.make(`evt_${id}`),
created: Date.now(),
type: Agent.Event.Updated.type,
data: {},
})
const internal = (value: string): Event.Payload<typeof Internal> => ({
id: Event.ID.create(),
created: Date.now(),
type: Internal.type,
data: { value },
})
function makeSource() {
let subscriber: Bus.Subscriber | undefined
return {
observe: (next: Bus.Subscriber) =>
Effect.sync(() => {
subscriber = next
return Effect.sync(() => {
if (subscriber === next) subscriber = undefined
})
}),
publish: (event: Event.Payload) => Effect.suspend(() => (subscriber ? subscriber(event) : Effect.void)),
}
}
describe("EventFeed", () => {
test("preserves the public SSE frame encoding", () => {
const payload = event("wire")
expect(EventFeed.frame(payload)).toBe(`data: ${JSON.stringify(payload)}\n\n`)
})
it.effect("encodes once and delivers the same frame to every subscriber", () =>
Effect.gen(function* () {
let encodes = 0
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, {
encode: (event) => {
encodes += 1
return event.type
},
})
const first = (yield* feed.subscribe()).events
const second = (yield* feed.subscribe()).events
const left = yield* first.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
const right = yield* second.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
yield* source.publish(event("example"))
expect([Array.from(yield* Fiber.join(left)), Array.from(yield* Fiber.join(right))]).toEqual([
[Agent.Event.Updated.type],
[Agent.Event.Updated.type],
])
expect(encodes).toBe(1)
}),
)
it.effect("delivers only the requested event types to filtered subscribers", () =>
Effect.gen(function* () {
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, { encode: (event) => event.type })
const filtered = (yield* feed.subscribe([Credential.Event.Switched.type])).events
const all = (yield* feed.subscribe()).events
const left = yield* filtered.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
const right = yield* all.pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped)
yield* source.publish(event("ignored"))
yield* source.publish({
id: Event.ID.create(),
created: Date.now(),
type: Credential.Event.Switched.type,
data: {
credentialID: Credential.ID.make("cred_test"),
integrationID: IntegrationID.make("openai"),
},
})
expect(Array.from(yield* Fiber.join(left))).toEqual([Credential.Event.Switched.type])
expect(Array.from(yield* Fiber.join(right))).toEqual([Agent.Event.Updated.type, Credential.Event.Switched.type])
}),
)
it.effect("fails only the subscriber that exceeds its lag capacity", () =>
Effect.gen(function* () {
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, {
capacity: 1,
encode: (event) => event.id,
})
const slow = (yield* feed.subscribe()).events
const fast = (yield* feed.subscribe()).events
const first = yield* Deferred.make<void>()
const second = yield* Deferred.make<void>()
const received = new Array<string>()
const fastFiber = yield* fast.pipe(
Stream.take(3),
Stream.runForEach((frame) =>
Effect.sync(() => received.push(frame)).pipe(
Effect.andThen(
frame === "evt_one"
? Deferred.succeed(first, undefined)
: frame === "evt_two"
? Deferred.succeed(second, undefined)
: Effect.void,
),
),
),
Effect.forkScoped,
)
yield* source.publish(event("one"))
yield* Deferred.await(first)
yield* source.publish(event("two"))
yield* Deferred.await(second)
yield* source.publish(event("three"))
yield* Fiber.join(fastFiber)
const result = yield* slow.pipe(Stream.runCollect, Effect.exit)
expect(received).toEqual(["evt_one", "evt_two", "evt_three"])
expect(Exit.isFailure(result)).toBeTrue()
if (Exit.isSuccess(result)) return
expect(Option.getOrUndefined(Exit.findErrorOption(result))).toBeInstanceOf(EventFeed.SubscriberOverflowError)
}),
)
it.effect("delivers global credential events to public subscribers", () =>
Effect.gen(function* () {
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, { encode: (event) => event.type })
const stream = (yield* feed.subscribe()).events
const received = yield* stream.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
yield* source.publish({
id: Event.ID.create(),
created: Date.now(),
type: Credential.Event.Switched.type,
data: {
credentialID: Credential.ID.make("cred_test"),
integrationID: IntegrationID.make("openai"),
},
})
expect(Array.from(yield* Fiber.join(received))).toEqual([Credential.Event.Switched.type])
}),
)
it.effect("filters internal events before they consume subscriber capacity", () =>
Effect.gen(function* () {
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, { capacity: 1, encode: (event) => event.type })
const stream = (yield* feed.subscribe()).events
yield* source.publish(internal("one"))
yield* source.publish(internal("two"))
yield* source.publish(event("public"))
expect(Array.from(yield* stream.pipe(Stream.take(1), Stream.runCollect))).toEqual([Agent.Event.Updated.type])
}),
)
it.effect("disconnects current subscribers after an encoding failure and continues for later subscribers", () =>
Effect.gen(function* () {
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, {
encode: (event) => {
if (event.id === Event.ID.make("evt_bad")) throw new Error("invalid event")
return event.id
},
})
const current = (yield* feed.subscribe()).events
const failed = yield* current.pipe(Stream.runCollect, Effect.exit, Effect.forkScoped)
yield* source.publish(event("bad"))
const exit = yield* Fiber.join(failed)
const next = (yield* feed.subscribe()).events
const received = yield* next.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
yield* source.publish(event("good"))
expect(Exit.isFailure(exit)).toBeTrue()
if (Exit.isSuccess(exit)) return
expect(Option.getOrUndefined(Exit.findErrorOption(exit))).toBeInstanceOf(EventFeed.EncodingError)
expect(Array.from(yield* Fiber.join(received))).toEqual(["evt_good"])
}),
)
})
it.live("each stream gets its own ID, and a failing extension never fails it", () =>
Effect.gen(function* () {
const source = makeSource()
const opened: Array<{ stream: string; send: Parameters<EventFeed.Extension["open"]>[1] }> = []
const feed = yield* EventFeed.make(source.observe, {
extensions: [
{ open: () => Effect.die(new Error("broken")) },
{ open: (stream, send) => Effect.sync(() => void opened.push({ stream, send })) },
],
})
const first = yield* feed.subscribe()
const second = yield* feed.subscribe()
expect(opened.map((item) => item.stream)).toEqual([first.id, second.id])
expect(first.id).not.toBe(second.id)
// A cyclic payload cannot be encoded; it is dropped instead of failing the stream.
const cyclic: Record<string, unknown> = {}
cyclic.self = cyclic
const send = opened[0]?.send
if (send) yield* send({ ...event("bad"), data: cyclic })
yield* source.publish(event("ok"))
const [frame] = yield* first.events.pipe(
Stream.take(1),
Stream.runCollect,
Effect.map((frames) => Array.from(frames)),
)
expect(frame && JSON.parse(frame.slice("data: ".length)).id).toBe("evt_ok")
}),
)