diff --git a/packages/core/test/bus.test.ts b/packages/core/test/bus.test.ts index dd35c2b51d0..25c4e5f462f 100644 --- a/packages/core/test/bus.test.ts +++ b/packages/core/test/bus.test.ts @@ -296,6 +296,13 @@ describe("Bus", () => { expect( yield* db.select().from(EventSequenceTable).where(eq(EventSequenceTable.aggregate_id, aggregateID)).all(), ).toEqual([{ aggregate_id: aggregateID, seq: 0, owner_id: null }]) + expect(yield* bus.log({ aggregateID, follow: true }).pipe(Stream.take(1), Stream.runCollect)).toEqual([ + { type: "log.synced", aggregateID, seq: Event.Seq.make(0), persist: false }, + ]) + yield* bus.publish(SyncMessage, { id: aggregateID, text: "next" }) + expect(yield* Stream.runCollect(bus.log({ aggregateID, after: 0 }))).toEqual([ + { type: "log.synced", aggregateID, seq: Event.Seq.make(1), persist: false }, + ]) }), ) diff --git a/packages/core/test/session-log.test.ts b/packages/core/test/session-log.test.ts index 3a26e7c16e9..8398fca12c4 100644 --- a/packages/core/test/session-log.test.ts +++ b/packages/core/test/session-log.test.ts @@ -18,33 +18,19 @@ import { SessionTable } from "@opencode/core/session/sql" import { testEffect } from "./lib/effect" import { globalProjectNode } from "./lib/project" -const layer = (persist: boolean) => +const it = testEffect( AppNodeBuilder.build( LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node, Session.node]), [ - Bus.node.replace(Bus.configured({ persist })), + Bus.node.replace(Bus.configured({ persist: true })), Project.node.replace(globalProjectNode), SessionExecution.node.replace(SessionExecution.noopLayer), ], - ) -const it = testEffect(layer(true)) -const withoutPersistence = testEffect(layer(false)) + ), +) const location = Location.Ref.make({ directory: AbsolutePath.make("/project") }) describe("Session.log", () => { - withoutPersistence.effect("reports disabled persistence despite an advancing aggregate watermark", () => - Effect.gen(function* () { - const session = yield* Session.Service - const created = yield* session.create({ location }) - const first = yield* session.log({ sessionID: created.id, follow: true }).pipe(Stream.take(1), Stream.runCollect) - expect(first).toEqual([{ type: "log.synced", aggregateID: created.id, seq: Event.Seq.make(0), persist: false }]) - - yield* session.rename({ sessionID: created.id, title: "not retained" }) - const resumed = yield* Stream.runCollect(session.log({ sessionID: created.id, after: 0 })) - expect(resumed).toEqual([{ type: "log.synced", aggregateID: created.id, seq: Event.Seq.make(1), persist: false }]) - }), - ) - it.effect("replays public session events and marks synced at the aggregate watermark", () => Effect.gen(function* () { const session = yield* Session.Service diff --git a/packages/server/test/process.test.ts b/packages/server/test/process.test.ts index 6613b301e18..5c95cd4930e 100644 --- a/packages/server/test/process.test.ts +++ b/packages/server/test/process.test.ts @@ -1,5 +1,6 @@ import { expect } from "bun:test" -import { Effect } from "effect" +import { Effect, Fiber } from "effect" +import { TestClock } from "effect/testing" import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http" import { it } from "../../core/test/lib/effect" import { ServerProcess } from "../src/process" @@ -111,38 +112,6 @@ it.live("authenticates API requests behind the frontend transform while allowing yield* Effect.promise(() => readUntil(reader, "installation.updated")) yield* Effect.promise(() => reader.cancel()) - const sessionID = Session.ID.create() - const created = yield* Effect.promise(() => - fetch(new URL("/api/session", HttpServer.formatAddress(server.address)), { - method: "POST", - headers: { - "content-type": "application/json", - authorization: `Basic ${btoa("opencode:secret")}`, - }, - body: JSON.stringify({ id: sessionID, title: "Log compression" }), - }), - ) - expect(created.status).toBe(200) - yield* Effect.promise(() => created.arrayBuffer()) - const log = yield* Effect.promise(() => - fetch( - new URL(`/api/experimental/session/${sessionID}/log?follow=true`, HttpServer.formatAddress(server.address)), - { - headers: { - "accept-encoding": "gzip", - authorization: `Basic ${btoa("opencode:secret")}`, - }, - }, - ), - ) - expect(log.status).toBe(200) - expect(log.headers.get("content-encoding")).toBeNull() - const logBody = log.body - if (!logBody) return yield* Effect.die(new Error("Log response has no body")) - const logReader = logBody.getReader() - yield* Effect.promise(() => readUntil(logReader, "log.synced")) - yield* Effect.promise(() => logReader.cancel()) - const missing = yield* Effect.promise(() => fetch(new URL("/missing", HttpServer.formatAddress(server.address)), { headers: { @@ -200,6 +169,79 @@ it.live("authenticates API requests behind the frontend transform while allowing }), ) +for (const persist of [false, true]) { + it.effect(`session log keeps SSE uncompressed and heartbeats followers (persist: ${persist})`, () => + Effect.gen(function* () { + const server = yield* ServerProcess.start({ + hostname: "127.0.0.1", + port: 0, + password: "secret", + database: { path: ":memory:" }, + fs: { filewatcher: false }, + config: { project: false }, + ...(persist ? { events: { persist } } : {}), + }) + const request = (path: string, method = "GET", body?: object) => + Effect.promise(() => + fetch(new URL(`/api/${path}`, HttpServer.formatAddress(server.address)), { + method, + headers: { + authorization: `Basic ${btoa("opencode:secret")}`, + "accept-encoding": "gzip", + "content-type": "application/json", + }, + body: JSON.stringify(body), + }), + ) + const id = Session.ID.create() + const missing = yield* request(`experimental/session/${id}/log?follow=true`) + expect(missing.status).toBe(404) + expect(missing.headers.get("content-type")).not.toContain("text/event-stream") + yield* Effect.promise(() => missing.arrayBuffer()) + const created = yield* request("session", "POST", { id, title: "Log test" }) + expect(created.status).toBe(200) + yield* Effect.promise(() => created.arrayBuffer()) + const replay = yield* request(`experimental/session/${id}/log?follow=false`) + const text = yield* Effect.promise(() => replay.text()) + expect(text).toContain('"type":"log.synced"') + expect(text).toContain(`"persist":${persist}`) + expect(text.includes('"type":"session.created"')).toBe(persist) + expect(text).not.toContain(": heartbeat") + + const response = yield* request(`experimental/session/${id}/log?after=0&follow=true`) + expect(response.status).toBe(200) + expect(response.headers.get("content-encoding")).toBeNull() + expect(response.headers.get("cache-control")).toBe("no-cache, no-transform") + expect(response.headers.get("x-accel-buffering")).toBe("no") + const body = response.body + if (!body) return yield* Effect.die("Missing SSE body") + const reader = yield* Effect.acquireRelease( + Effect.sync(() => body.getReader()), + (reader) => Effect.promise(() => reader.cancel()), + ) + const synced = yield* Effect.promise(() => readUntil(reader, "log.synced")) + expect(synced).toContain(`"persist":${persist}`) + expect(synced).not.toContain(": heartbeat") + const next = yield* Effect.promise(() => reader.read()).pipe(Effect.forkChild({ startImmediately: true })) + yield* Effect.yieldNow + expect(next.pollUnsafe()).toBeUndefined() + yield* TestClock.adjust("14 seconds") + expect(next.pollUnsafe()).toBeUndefined() + yield* TestClock.adjust("1 second") + expect(new TextDecoder().decode((yield* Fiber.join(next)).value)).toBe(": heartbeat\n\n") + const again = yield* Effect.promise(() => reader.read()).pipe(Effect.forkChild({ startImmediately: true })) + yield* TestClock.adjust("15 seconds") + expect(new TextDecoder().decode((yield* Fiber.join(again)).value)).toBe(": heartbeat\n\n") + if (!persist) return + const updated = yield* request(`session/${id}`, "PATCH", { title: "After heartbeat" }) + expect(updated.status).toBe(204) + yield* Effect.promise(() => updated.arrayBuffer()) + const event = yield* Effect.promise(() => readUntil(reader, "session.renamed")) + expect(event).toContain('"seq":1') + }), + ) +} + it.live("pairing links sign in browsers with a cookie and API clients with a token", () => Effect.gen(function* () { const server = yield* ServerProcess.start({ @@ -266,7 +308,8 @@ async function readUntil(reader: ReadableStreamDefaultReader, expect while (true) { const next = await reader.read() if (next.done) throw new Error(`Event stream ended before ${expected}`) - if (new TextDecoder().decode(next.value).includes(expected)) return + const text = new TextDecoder().decode(next.value) + if (text.includes(expected)) return text } } diff --git a/packages/server/test/session-log.test.ts b/packages/server/test/session-log.test.ts deleted file mode 100644 index cb1ae681d3c..00000000000 --- a/packages/server/test/session-log.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { expect } from "bun:test" -import { Clock, Context, Effect, Fiber, Layer, Schema } from "effect" -import { TestClock } from "effect/testing" -import { HttpEffect, HttpRouter, HttpServer } from "effect/http" -import { Session } from "@opencode/schema/session" -import { it } from "../../core/test/lib/effect" -import { createRoutes } from "../src/routes" - -const setup = Effect.fnUntraced(function* (persist?: boolean) { - const routes = createRoutes({ - app: { version: "test" }, - database: { path: ":memory:" }, - fs: { filewatcher: false }, - config: { project: false }, - ...(persist === undefined ? {} : { events: { persist } }), - }) - const context = yield* Layer.build(routes.pipe(Layer.provide(HttpServer.layerServices))) - // Web handlers run outside the test fiber; carry its clock into the response stream. - const clock = yield* Clock.Clock - const handler = Context.get(context, HttpRouter.HttpRouter) - .asHttpEffect() - .pipe(HttpEffect.toWebHandlerWith(Context.add(context, Clock.Clock, clock))) - const response = yield* Effect.promise(() => - handler( - new Request("http://opencode.local/api/session", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ title: "Log test" }), - }), - ), - ) - expect(response.status).toBe(200) - const created = Schema.decodeUnknownSync(Schema.Struct({ data: Schema.toEncoded(Session.Info) }))( - yield* Effect.promise(() => response.json()), - ) - return { handler, sessionID: created.data.id } -}) - -it.live("advertises default persistence off and completes a non-following HTTP log", () => - Effect.gen(function* () { - const server = yield* setup() - const response = yield* Effect.promise(() => - server.handler( - new Request(`http://opencode.local/api/experimental/session/${server.sessionID}/log?follow=false`), - ), - ) - expect(response.status).toBe(200) - const text = yield* Effect.promise(() => response.text()) - expect(text).toContain('"type":"log.synced"') - expect(text).toContain('"persist":false') - expect(text).not.toContain('"type":"session.created"') - expect(text).not.toContain(": heartbeat") - }), -) - -it.effect("heartbeats a quiet followed log without adding a cursor or data event", () => - Effect.gen(function* () { - const server = yield* setup(true) - const response = yield* Effect.promise(() => - server.handler( - new Request(`http://opencode.local/api/experimental/session/${server.sessionID}/log?after=0&follow=true`), - ), - ) - expect(response.status).toBe(200) - expect(response.headers.get("cache-control")).toBe("no-cache, no-transform") - expect(response.headers.get("x-accel-buffering")).toBe("no") - const body = response.body - if (!body) return yield* Effect.die("Missing SSE body") - const reader = yield* Effect.acquireRelease( - Effect.sync(() => body.getReader()), - (reader) => Effect.promise(() => reader.cancel()), - ) - const first = yield* Effect.promise(() => reader.read()) - expect(new TextDecoder().decode(first.value)).toContain('"persist":true') - - const next = yield* Effect.promise(() => reader.read()).pipe(Effect.forkChild({ startImmediately: true })) - yield* Effect.yieldNow - expect(next.pollUnsafe()).toBeUndefined() - yield* TestClock.adjust("14 seconds") - expect(next.pollUnsafe()).toBeUndefined() - yield* TestClock.adjust("1 second") - expect(new TextDecoder().decode((yield* Fiber.join(next)).value)).toBe(": heartbeat\n\n") - - const again = yield* Effect.promise(() => reader.read()).pipe(Effect.forkChild({ startImmediately: true })) - yield* TestClock.adjust("15 seconds") - expect(new TextDecoder().decode((yield* Fiber.join(again)).value)).toBe(": heartbeat\n\n") - - const updated = yield* Effect.promise(() => - server.handler( - new Request(`http://opencode.local/api/session/${server.sessionID}`, { - method: "PATCH", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ title: "After heartbeat" }), - }), - ), - ) - expect(updated.status).toBe(204) - yield* Effect.promise(() => updated.arrayBuffer()) - const event = new TextDecoder().decode((yield* Effect.promise(() => reader.read())).value) - expect(event).toContain('"type":"session.renamed"') - expect(event).toContain('"seq":1') - }), -) - -it.live("keeps unknown-session responses as HTTP errors when following", () => - Effect.gen(function* () { - const server = yield* setup() - const response = yield* Effect.promise(() => - server.handler( - new Request(`http://opencode.local/api/experimental/session/${Session.ID.create()}/log?follow=true`), - ), - ) - expect(response.status).toBe(404) - expect(response.headers.get("content-type")).not.toContain("text/event-stream") - }), -) diff --git a/packages/server/test/sse-failure.test.ts b/packages/server/test/sse-failure.test.ts index 7914f4781ec..adf5622f5da 100644 --- a/packages/server/test/sse-failure.test.ts +++ b/packages/server/test/sse-failure.test.ts @@ -15,7 +15,7 @@ import { schemaErrorLayer } from "../src/middleware/schema-error" const LogApi = HttpApi.make("log").add( HttpApiGroup.make("server.session").add(ClientApi.groups["server.session"].endpoints["session.log"]), ) -const synced = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1), persist: true } +const synced = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1) } const handler = HttpRouter.toWebHandler( HttpApiBuilder.layer(LogApi).pipe(