| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163 |
- import { describe, expect } from "bun:test"
- import { DateTime, Effect, Fiber, Layer, LayerMap, Schema, Stream } from "effect"
- import { mkdtemp, rm } from "fs/promises"
- import { tmpdir } from "os"
- import path from "path"
- import { pathToFileURL } from "url"
- import { eq } from "drizzle-orm"
- import { Database } from "@opencode-ai/core/database/database"
- import { Agent } from "@opencode-ai/core/agent"
- import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
- import { LayerNode } from "@opencode-ai/util/effect/layer-node"
- import { Bus } from "@opencode-ai/core/bus"
- import { EventTable } from "@opencode-ai/core/event/sql"
- import { SessionEvent } from "@opencode-ai/core/session/event"
- import { Model } from "@opencode-ai/core/model"
- import { Provider } from "@opencode-ai/core/provider"
- import { Project } from "@opencode-ai/core/project"
- import { ProjectTable } from "@opencode-ai/core/project/sql"
- import { AbsolutePath } from "@opencode-ai/core/schema"
- import { Session } from "@opencode-ai/core/session"
- import { SessionMessage } from "@opencode-ai/core/session/message"
- import { SessionProjector } from "@opencode-ai/core/session/projector"
- import { SessionExecution } from "@opencode-ai/core/session/execution"
- import { SessionPending } from "@opencode-ai/core/session/pending"
- import { SessionPendingTable, SessionMessageTable, SessionTable } from "@opencode-ai/core/session/sql"
- import { SessionStore } from "@opencode-ai/core/session/store"
- import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
- import type { LocationServices } from "@opencode-ai/core/location-services"
- import { Image } from "@opencode-ai/core/image"
- import { testEffect } from "./lib/effect"
- const executionCalls: Session.ID[] = []
- const interruptCalls: Session.ID[] = []
- const wakeCalls: Session.ID[] = []
- const activeSessions = new Set<Session.ID>()
- const execution = Layer.succeed(
- SessionExecution.Service,
- SessionExecution.Service.of({
- active: Effect.sync(() => new Set(activeSessions)),
- resume: (sessionID) =>
- Effect.sync(() => {
- executionCalls.push(sessionID)
- }),
- interrupt: (sessionID) =>
- Effect.sync(() => {
- interruptCalls.push(sessionID)
- }),
- wake: (sessionID) =>
- Effect.sync(() => {
- wakeCalls.push(sessionID)
- }),
- awaitIdle: () => Effect.void,
- }),
- )
- const locations = Layer.effect(
- LocationServiceMap.Service,
- LayerMap.make(
- () =>
- // Attachment admission only needs the location-scoped Image service.
- // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
- Layer.mock(Image.Service, {
- normalize: (_resource, content) =>
- Effect.succeed(content.content.length > 5 * 1024 * 1024 ? { ...content, content: "AA==" } : content),
- }) as unknown as Layer.Layer<LocationServices>,
- ),
- )
- const it = testEffect(
- AppNodeBuilder.build(
- LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node, Session.node]),
- [
- [Bus.node, Bus.configured({ persist: true })],
- [SessionExecution.node, execution],
- [LocationServiceMap.node, locations],
- ],
- ),
- )
- const sessionID = Session.ID.make("ses_prompt_test")
- const messageID = SessionMessage.ID.create()
- const setup = Effect.gen(function* () {
- const { db } = yield* Database.Service
- yield* db
- .insert(ProjectTable)
- .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
- .onConflictDoNothing()
- .run()
- .pipe(Effect.orDie)
- yield* db
- .insert(SessionTable)
- .values({
- id: sessionID,
- project_id: Project.ID.global,
- slug: "test",
- directory: "/project",
- title: "test",
- version: "test",
- })
- .onConflictDoNothing()
- .run()
- .pipe(Effect.orDie)
- })
- const admitted = (id: SessionMessage.ID) => Database.Service.use(({ db }) => SessionPending.find(db, id))
- const admittedCount = Database.Service.use(({ db }) =>
- db
- .select()
- .from(SessionPendingTable)
- .all()
- .pipe(
- Effect.orDie,
- Effect.map((rows) => rows.length),
- ),
- )
- const eventCount = (type: string) =>
- Database.Service.use(({ db }) =>
- db
- .select()
- .from(EventTable)
- .where(eq(EventTable.type, type))
- .all()
- .pipe(
- Effect.orDie,
- Effect.map((rows) => rows.length),
- ),
- )
- const encodeMessage = Schema.encodeSync(SessionMessage.Info)
- const assistantRow = (id: SessionMessage.ID, seq: number) => {
- const {
- id: _,
- type,
- ...data
- } = encodeMessage(
- SessionMessage.Assistant.make({
- id,
- type: "assistant",
- agent: Agent.ID.make("build"),
- model: { id: Model.ID.make("model"), providerID: Provider.ID.make("provider") },
- content: [],
- time: { created: DateTime.makeUnsafe(0) },
- }),
- )
- return { id, session_id: sessionID, type, seq, time_created: 0, data }
- }
- describe("Session.prompt", () => {
- it.effect("exposes the execution registry", () =>
- Effect.gen(function* () {
- activeSessions.add(sessionID)
- expect(Array.from(yield* (yield* Session.Service).active)).toEqual([sessionID])
- }).pipe(Effect.ensuring(Effect.sync(() => activeSessions.clear()))),
- )
- it.effect("delegates execution continuation through SessionExecution", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- executionCalls.length = 0
- wakeCalls.length = 0
- yield* session.resume(sessionID)
- expect(executionCalls).toEqual([sessionID])
- expect(wakeCalls).toEqual([])
- }),
- )
- it.effect("delegates process-local interruption through SessionExecution", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- interruptCalls.length = 0
- yield* session.interrupt(sessionID)
- expect(interruptCalls).toEqual([sessionID])
- expect(yield* session.messages({ sessionID })).toEqual([])
- }),
- )
- it.effect("delegates interruption without requiring a recorded Session", () =>
- Effect.gen(function* () {
- const session = yield* Session.Service
- interruptCalls.length = 0
- yield* session.interrupt(Session.ID.make("ses_missing"))
- expect(interruptCalls).toEqual([Session.ID.make("ses_missing")])
- }),
- )
- it.effect("durably admits one user message before transcript promotion", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const message = yield* session.prompt({
- sessionID,
- text: "Fix the failing tests",
- resume: false,
- })
- expect(message.data.text).toBe("Fix the failing tests")
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(yield* admitted(message.id)).toMatchObject({
- id: message.id,
- sessionID,
- type: "user",
- data: { text: "Fix the failing tests" },
- delivery: "steer",
- })
- }),
- )
- it.effect("commits a staged revert before admitting a new prompt", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const boundary = yield* session.prompt({
- sessionID,
- text: "boundary",
- resume: false,
- })
- yield* SessionPending.promote(db, bus, sessionID, "steer")
- const stale = SessionMessage.ID.make("msg_stale_assistant")
- yield* db.insert(SessionMessageTable).values(assistantRow(stale, 100)).run().pipe(Effect.orDie)
- yield* bus.publish(SessionEvent.RevertEvent.Staged, {
- sessionID,
- revert: { messageID: boundary.id, files: [] },
- })
- expect((yield* session.get(sessionID)).revert?.messageID).toBe(boundary.id)
- yield* session.prompt({ sessionID, text: "after revert", resume: false })
- expect((yield* session.get(sessionID)).revert).toBeUndefined()
- expect(
- (yield* db.select({ id: SessionMessageTable.id }).from(SessionMessageTable).all().pipe(Effect.orDie)).map(
- (row) => row.id,
- ),
- ).not.toContainAnyValues([boundary.id, stale])
- expect(yield* SessionPending.find(db, boundary.id)).toBeUndefined()
- }),
- )
- it.effect("holds synthetic input behind a staged revert and discards it when committed", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const boundary = yield* session.prompt({
- sessionID,
- text: "boundary",
- resume: false,
- })
- yield* SessionPending.promote(db, bus, sessionID, "steer")
- yield* bus.publish(SessionEvent.RevertEvent.Staged, {
- sessionID,
- revert: { messageID: boundary.id, files: [] },
- })
- wakeCalls.length = 0
- const completion = yield* session.synthetic({ sessionID, text: "stale completion" })
- expect(wakeCalls).toEqual([])
- expect(yield* SessionPending.find(db, completion.id)).toMatchObject({ type: "synthetic" })
- yield* session.revert.commit(sessionID)
- expect(yield* SessionPending.find(db, completion.id)).toBeUndefined()
- }),
- )
- it.effect("resolves attachment MIME before admission", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const uri =
- "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
- const message = yield* session.prompt({
- sessionID,
- text: "Inspect this image",
- files: [{ uri, name: "image.png", mention: { start: 8, end: 17, text: "[Image 1]" } }],
- resume: false,
- })
- expect(message.data.files).toEqual([
- {
- data: uri.slice(uri.indexOf(",") + 1),
- mime: "image/png",
- source: { type: "inline" },
- name: "image.png",
- mention: { start: 8, end: 17, text: "[Image 1]" },
- },
- ])
- const stored = yield* admitted(message.id)
- expect(stored?.type).toBe("user")
- if (stored?.type === "user") expect(stored.data.files).toEqual(message.data.files)
- }),
- )
- it.effect("materializes selected source file content", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const directory = import.meta.dir
- const source = path.join(directory, "session-prompt.test.ts")
- const sourceUri = pathToFileURL(source)
- sourceUri.searchParams.set("start", "1")
- sourceUri.searchParams.set("end", "1")
- const message = yield* session.prompt({
- sessionID,
- text: "Inspect this",
- files: [{ uri: sourceUri.href, name: "main.ts" }],
- resume: false,
- })
- expect(message.data.files).toHaveLength(1)
- expect(message.data.files?.[0]).toMatchObject({
- mime: "text/plain",
- source: { type: "uri", uri: sourceUri.href },
- name: "main.ts",
- })
- expect(
- Buffer.from(message.data.files?.[0]?.data ?? "", "base64")
- .toString("utf8")
- .replace(/\r$/, ""),
- ).toBe('import { describe, expect } from "bun:test"')
- }),
- )
- it.effect("materializes directories as directory attachments", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const uri = pathToFileURL(import.meta.dir).href
- const message = yield* session.prompt({
- sessionID,
- text: "Inspect this",
- files: [{ uri, name: "source" }],
- resume: false,
- })
- expect(message.data.files).toHaveLength(1)
- expect(message.data.files?.[0]).toMatchObject({
- mime: "application/x-directory",
- source: { type: "uri", uri },
- name: "source",
- })
- expect(Buffer.from(message.data.files?.[0]?.data ?? "", "base64").toString("utf8")).toContain(
- "session-prompt.test.ts",
- )
- }),
- )
- it.effect("materializes local image content before admission", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const directory = yield* Effect.acquireRelease(
- Effect.promise(() => mkdtemp(path.join(tmpdir(), "opencode-session-prompt-"))),
- (directory) => Effect.promise(() => rm(directory, { recursive: true, force: true })),
- )
- const source = path.join(directory, "image.png")
- const bytes = Buffer.from(
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
- "base64",
- )
- yield* Effect.promise(() => Bun.write(source, bytes))
- const message = yield* session.prompt({
- sessionID,
- text: "Inspect this image",
- files: [{ uri: pathToFileURL(source).href }],
- resume: false,
- })
- expect(message.data.files).toEqual([
- {
- data: bytes.toString("base64"),
- mime: "image/png",
- source: { type: "uri", uri: pathToFileURL(source).href },
- name: "image.png",
- },
- ])
- const stored = yield* admitted(message.id)
- expect(stored?.type === "user" ? stored.data.files : undefined).toEqual(message.data.files)
- }),
- )
- it.effect("normalizes large image content before validating persisted Base64", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const pixel = Buffer.from(
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
- "base64",
- )
- const bytes = Buffer.concat([pixel, Buffer.alloc(4_323_030 - pixel.length)])
- const data = bytes.toString("base64")
- expect(data).toHaveLength(5_764_040)
- const message = yield* session.prompt({
- sessionID,
- text: "Inspect this image",
- files: [{ uri: `data:image/png;base64,${data}` }],
- resume: false,
- })
- expect(message.data.files).toEqual([
- {
- data: "AA==",
- mime: "image/png",
- source: { type: "inline" },
- },
- ])
- }),
- )
- it.effect("sniffs data URL content instead of trusting its declared MIME", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const uri = `data:video/mp2t;base64,${Buffer.from("export const value = 1\n").toString("base64")}`
- const message = yield* session.prompt({
- sessionID,
- text: "Inspect this",
- files: [{ uri, name: "main.ts" }],
- resume: false,
- })
- expect(message.data.files).toEqual([
- {
- data: Buffer.from("export const value = 1\n").toString("base64"),
- mime: "text/plain",
- source: { type: "inline" },
- name: "main.ts",
- },
- ])
- }),
- )
- it.effect("rejects malformed base64 data URLs", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const uri = "data:image/png;base64,not-base64"
- const error = yield* session
- .prompt({
- sessionID,
- text: "Inspect this",
- files: [{ uri, name: "image.png" }],
- resume: false,
- })
- .pipe(Effect.flip)
- expect(error).toMatchObject({
- _tag: "Session.AttachmentError",
- uri,
- message: "Invalid attachment data URL",
- })
- }),
- )
- it.effect("streams durable Session events after an aggregate sequence", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const publicEvents = (input: { sessionID: Session.ID; after?: number }) =>
- session
- .log({ ...input, follow: true })
- .pipe(Stream.filter((item): item is SessionEvent.DurableEvent => !Bus.isSynced(item)))
- const fiber = yield* publicEvents({ sessionID }).pipe(Stream.take(4), Stream.runCollect, Effect.forkScoped)
- yield* Effect.yieldNow
- yield* session.prompt({ sessionID, text: "First", resume: false })
- yield* session.prompt({ sessionID, text: "Second", resume: false })
- yield* SessionPending.promote(db, bus, sessionID, "steer")
- const streamed = Array.from(yield* Fiber.join(fiber))
- expect(streamed.map((event): [number | undefined, string] => [event.durable?.seq, event.type])).toEqual([
- [0, "session.input.admitted"],
- [1, "session.input.admitted"],
- [2, "session.input.promoted"],
- [3, "session.input.promoted"],
- ])
- expect(
- Array.from(
- yield* publicEvents({ sessionID, after: streamed[0].durable?.seq }).pipe(Stream.take(1), Stream.runCollect),
- ).map((event): [number | undefined, string] => [event.durable?.seq, event.type]),
- ).toEqual([[1, "session.input.admitted"]])
- }),
- )
- it.effect("resumes through a recorded message without appending another prompt", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const message = yield* session.prompt({
- sessionID,
- text: "Fix the failing tests",
- resume: false,
- })
- executionCalls.length = 0
- wakeCalls.length = 0
- yield* session.resume(sessionID)
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(yield* admitted(message.id)).not.toHaveProperty("promotedSeq")
- expect(executionCalls).toEqual([sessionID])
- expect(wakeCalls).toEqual([])
- }),
- )
- it.effect("records distinct messages when the ID is omitted", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const input = { sessionID, text: "Fix the failing tests", resume: false }
- const first = yield* session.prompt(input)
- const second = yield* session.prompt(input)
- expect(second.id).not.toBe(first.id)
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(yield* admittedCount).toBe(2)
- }),
- )
- it.effect("returns the original recorded message when the ID is retried", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const input = {
- sessionID,
- id: messageID,
- text: "Fix the failing tests",
- resume: false,
- }
- const first = yield* session.prompt(input)
- const retried = yield* session.prompt(input)
- expect(retried).toEqual(first)
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(yield* admittedCount).toBe(1)
- }),
- )
- it.effect("reconciles an exact retry from the promoted message without admission history", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const input = { sessionID, id: messageID, text: "Fix the failing tests", resume: false }
- const first = yield* session.prompt(input)
- yield* SessionPending.promote(db, bus, sessionID, "steer")
- yield* db
- .delete(EventTable)
- .where(eq(EventTable.aggregate_id, sessionID))
- .run()
- .pipe(Effect.orDie)
- const retried = yield* session.prompt(input)
- expect(retried).toMatchObject({ id: first.id, type: "user", data: { text: first.data.text } })
- expect(yield* session.messages({ sessionID })).toMatchObject([
- { id: messageID, type: "user", text: "Fix the failing tests" },
- ])
- }),
- )
- it.effect("ignores delivery when retrying a promoted message", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const input = { sessionID, id: messageID, text: "Fix the failing tests", resume: false }
- yield* session.prompt(input)
- yield* SessionPending.promote(db, bus, sessionID, "steer")
- const retried = yield* session.prompt({ ...input, delivery: "queue" })
- expect(retried).toMatchObject({ id: messageID, type: "user", data: { text: input.text } })
- expect(yield* admitted(messageID)).toBeUndefined()
- }),
- )
- it.effect("wakes execution when an exact prompt retry recovers a committed message", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const input = {
- sessionID,
- id: messageID,
- text: "Recover committed prompt",
- resume: false,
- }
- const first = yield* session.prompt(input)
- wakeCalls.length = 0
- const retried = yield* session.prompt({ ...input, resume: true })
- expect(retried).toEqual(first)
- expect(wakeCalls).toEqual([sessionID])
- }),
- )
- it.effect("rejects reuse of one ID with a different prompt", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- yield* session.prompt({
- sessionID,
- id: messageID,
- text: "Fix the failing tests",
- })
- const failure = yield* session
- .prompt({
- sessionID,
- id: messageID,
- text: "Delete the failing tests",
- resume: false,
- })
- .pipe(Effect.flip)
- expect(failure._tag).toBe("Session.PromptConflictError")
- expect(yield* session.messages({ sessionID })).toHaveLength(0)
- expect(yield* admittedCount).toBe(1)
- }),
- )
- it.effect("rejects reuse of one ID with a different delivery mode", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- yield* session.prompt({
- id: messageID,
- sessionID,
- text: "Fix the failing tests",
- resume: false,
- })
- const failure = yield* session
- .prompt({
- id: messageID,
- sessionID,
- text: "Fix the failing tests",
- delivery: "queue",
- resume: false,
- })
- .pipe(Effect.flip)
- expect(failure._tag).toBe("Session.PromptConflictError")
- }),
- )
- it.effect("returns one recorded message to concurrent exact retries", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const input = {
- sessionID,
- id: messageID,
- text: "Fix the failing tests",
- resume: false,
- }
- const messages = yield* Effect.all([session.prompt(input), session.prompt(input)], { concurrency: "unbounded" })
- expect(messages[1]).toEqual(messages[0])
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(yield* admittedCount).toBe(1)
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputAdmitted.type, 1))).toBe(1)
- }),
- )
- it.effect("promotes one message once under concurrent promotion attempts", () =>
- Effect.gen(function* () {
- yield* setup
- const { db } = yield* Database.Service
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- yield* session.prompt({
- id: messageID,
- sessionID,
- text: "Promote once",
- resume: false,
- })
- yield* Effect.all(
- [SessionPending.promote(db, bus, sessionID, "steer"), SessionPending.promote(db, bus, sessionID, "steer")],
- { concurrency: "unbounded" },
- )
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputPromoted.type, 1))).toBe(1)
- expect(yield* admitted(messageID)).toBeUndefined()
- expect(yield* session.messages({ sessionID })).toMatchObject([
- { id: messageID, type: "user", text: "Promote once" },
- ])
- }),
- )
- it.effect("reprojects pending inbox input without scheduling execution", () =>
- Effect.gen(function* () {
- yield* setup
- const { db } = yield* Database.Service
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- wakeCalls.length = 0
- yield* session.prompt({
- id: messageID,
- sessionID,
- text: "Replay pending",
- resume: false,
- })
- const syntheticID = SessionMessage.ID.create()
- yield* session.synthetic({ id: syntheticID, sessionID, text: "Replay synthetic", resume: false })
- const recorded = yield* db
- .select()
- .from(EventTable)
- .where(eq(EventTable.aggregate_id, sessionID))
- .all()
- .pipe(Effect.orDie)
- yield* bus.remove(sessionID)
- yield* db
- .delete(SessionPendingTable)
- .where(eq(SessionPendingTable.session_id, sessionID))
- .run()
- .pipe(Effect.orDie)
- yield* db
- .delete(SessionMessageTable)
- .where(eq(SessionMessageTable.session_id, sessionID))
- .run()
- .pipe(Effect.orDie)
- yield* bus.replayAll(
- recorded.map((event) => ({
- id: event.id,
- created: DateTime.makeUnsafe(event.created),
- aggregateID: event.aggregate_id,
- seq: event.seq,
- type: event.type,
- data: event.data,
- })),
- )
- expect(yield* admitted(messageID)).toMatchObject({
- id: messageID,
- type: "user",
- data: { text: "Replay pending" },
- })
- expect(yield* admitted(syntheticID)).toMatchObject({
- id: syntheticID,
- type: "synthetic",
- data: { text: "Replay synthetic" },
- })
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(wakeCalls).toEqual([])
- }),
- )
- it.effect("rejects reuse of one globally unique message ID across sessions", () =>
- Effect.gen(function* () {
- yield* setup
- const { db } = yield* Database.Service
- const session = yield* Session.Service
- const other = Session.ID.make("ses_prompt_other")
- yield* db
- .insert(SessionTable)
- .values({
- id: other,
- project_id: Project.ID.global,
- slug: "other",
- directory: "/project",
- title: "other",
- version: "test",
- })
- .onConflictDoNothing()
- .run()
- .pipe(Effect.orDie)
- yield* session.prompt({ id: messageID, sessionID, text: "Fix the failing tests", resume: false })
- const failure = yield* session
- .prompt({ id: messageID, sessionID: other, text: "Fix the failing tests", resume: false })
- .pipe(Effect.flip)
- expect(failure).toMatchObject({ _tag: "Session.PromptConflictError", sessionID: other, messageID })
- }),
- )
- it.effect("rejects a prompt ID already used by visible Session history", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const { db } = yield* Database.Service
- const {
- id: _,
- type,
- ...data
- } = encodeMessage({
- id: messageID,
- type: "synthetic",
- text: "Existing history",
- time: { created: DateTime.makeUnsafe(0) },
- })
- yield* db
- .insert(SessionMessageTable)
- .values({ id: messageID, session_id: sessionID, type, seq: 0, time_created: 0, data })
- .run()
- .pipe(Effect.orDie)
- const failure = yield* session
- .prompt({
- id: messageID,
- sessionID,
- text: "Conflicting prompt",
- resume: false,
- })
- .pipe(Effect.flip)
- expect(failure).toMatchObject({ _tag: "Session.PromptConflictError", sessionID, messageID })
- expect(yield* admitted(messageID)).toBeUndefined()
- }),
- )
- it.effect("starts execution by default after recording the prompt", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- executionCalls.length = 0
- wakeCalls.length = 0
- yield* session.prompt({ sessionID, text: "Run by default" })
- expect(executionCalls).toEqual([])
- expect(wakeCalls).toEqual([sessionID])
- }),
- )
- it.effect("starts execution when resume is explicitly true", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- executionCalls.length = 0
- wakeCalls.length = 0
- yield* session.prompt({
- sessionID,
- text: "Run explicitly",
- resume: true,
- })
- expect(executionCalls).toEqual([])
- expect(wakeCalls).toEqual([sessionID])
- }),
- )
- it.effect("only records the prompt when resume is false", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- executionCalls.length = 0
- wakeCalls.length = 0
- yield* session.prompt({ sessionID, text: "Do not run", resume: false })
- expect(executionCalls).toEqual([])
- expect(wakeCalls).toEqual([])
- }),
- )
- it.effect("treats prompt metadata as durable retry identity", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const input = {
- id: messageID,
- sessionID,
- text: "Deploy",
- metadata: { source: "api" },
- resume: false,
- }
- const first = yield* session.prompt(input)
- const retried = yield* session.prompt(input)
- const failure = yield* session.prompt({ ...input, metadata: { source: "plugin" } }).pipe(Effect.flip)
- expect(retried).toEqual(first)
- expect(first.data.metadata).toEqual({ source: "api" })
- expect(failure._tag).toBe("Session.PromptConflictError")
- }),
- )
- it.effect("durably admits synthetic input before transcript promotion", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const input = yield* session.synthetic({
- id: messageID,
- sessionID,
- text: "Background work completed",
- description: "shell completion",
- metadata: { job: "shell" },
- resume: false,
- })
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(yield* admitted(input.id)).toMatchObject({
- type: "synthetic",
- sessionID,
- delivery: "steer",
- data: {
- text: "Background work completed",
- description: "shell completion",
- metadata: { job: "shell" },
- },
- })
- yield* SessionPending.promote(db, bus, sessionID, "steer")
- expect(yield* session.messages({ sessionID })).toMatchObject([
- {
- id: messageID,
- type: "synthetic",
- text: "Background work completed",
- description: "shell completion",
- metadata: { job: "shell" },
- },
- ])
- }),
- )
- it.effect("reconciles exact synthetic retries and rejects conflicting reuse", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const database = yield* Database.Service
- const input = { id: messageID, sessionID, text: "Completed", resume: false }
- const entries = yield* Effect.all([session.synthetic(input), session.synthetic(input)], {
- concurrency: "unbounded",
- })
- yield* SessionPending.promote(database.db, bus, sessionID, "steer")
- const promotedRetry = yield* session.synthetic(input)
- const failure = yield* session.synthetic({ ...input, text: "Different completion" }).pipe(Effect.flip)
- expect(entries[1]).toEqual(entries[0])
- expect(promotedRetry).toMatchObject({ id: messageID, type: "synthetic", data: { text: "Completed" } })
- expect(failure).toMatchObject({ _tag: "Session.SyntheticConflictError", sessionID, inputID: messageID })
- expect(yield* admittedCount).toBe(0)
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputAdmitted.type, 1))).toBe(1)
- }),
- )
- it.effect("keeps queued input pending until the idle boundary", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const input = yield* session.synthetic({
- sessionID,
- text: "Queued completion",
- delivery: "queue",
- resume: false,
- })
- expect(input.delivery).toBe("queue")
- expect(yield* SessionPending.has(db, sessionID, "input")).toBe(true)
- expect(
- yield* SessionPending.promote(db, bus, sessionID, "steer"),
- ).toBe(0)
- expect(yield* session.messages({ sessionID })).toEqual([])
- expect(
- yield* SessionPending.promote(db, bus, sessionID, "input"),
- ).toBe(1)
- expect(yield* SessionPending.has(db, sessionID, "input")).toBe(false)
- expect(yield* session.messages({ sessionID })).toMatchObject([
- { id: input.id, type: "synthetic", text: "Queued completion" },
- ])
- }),
- )
- it.effect("promotes prompt and synthetic steers in admission order", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- yield* session.prompt({
- sessionID,
- text: "First prompt",
- resume: false,
- })
- yield* session.synthetic({ sessionID, text: "Background completion", resume: false })
- yield* session.prompt({
- sessionID,
- text: "Second prompt",
- resume: false,
- })
- yield* SessionPending.promote(db, bus, sessionID, "steer")
- expect(
- (yield* session.messages({ sessionID, order: "asc" })).map((message) =>
- message.type === "user" || message.type === "synthetic" ? message.text : message.type,
- ),
- ).toEqual(["First prompt", "Background completion", "Second prompt"])
- }),
- )
- })
- describe("Session.pending", () => {
- it.effect("fails for an unknown session", () =>
- Effect.gen(function* () {
- const session = yield* Session.Service
- expect(yield* session.pending(Session.ID.make("ses_missing")).pipe(Effect.flip)).toMatchObject({
- _tag: "Session.NotFoundError",
- })
- }),
- )
- it.effect("lists admitted work in admission order until promotion", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const bus = yield* Bus.Service
- const { db } = yield* Database.Service
- const first = yield* session.prompt({ sessionID, text: "First steer", resume: false })
- const queued = yield* session.synthetic({
- sessionID,
- text: "Queued completion",
- delivery: "queue",
- resume: false,
- })
- const second = yield* session.prompt({ sessionID, text: "Second steer", resume: false })
- expect(yield* session.pending(sessionID)).toMatchObject([
- { id: first.id, type: "user", delivery: "steer" },
- { id: queued.id, type: "synthetic", delivery: "queue" },
- { id: second.id, type: "user", delivery: "steer" },
- ])
- expect(
- yield* SessionPending.promote(db, bus, sessionID, "input"),
- ).toBe(2)
- expect(yield* session.pending(sessionID)).toMatchObject([{ id: queued.id, type: "synthetic" }])
- expect(
- yield* SessionPending.promote(db, bus, sessionID, "input"),
- ).toBe(1)
- expect(yield* session.pending(sessionID)).toEqual([])
- }),
- )
- it.effect("lists an unhandled compaction barrier until it settles", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const { db } = yield* Database.Service
- const barrier = yield* session.compact({ sessionID })
- expect(yield* SessionPending.has(db, sessionID, "any")).toBe(true)
- expect(yield* SessionPending.has(db, sessionID, "input")).toBe(false)
- expect(yield* session.pending(sessionID)).toMatchObject([{ id: barrier.id, type: "compaction" }])
- yield* SessionPending.settleCompaction(db, { sessionID })
- expect(yield* SessionPending.has(db, sessionID, "any")).toBe(false)
- expect(yield* session.pending(sessionID)).toEqual([])
- }),
- )
- it.effect("cancels pending input and allows its ID to be admitted again", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const inputID = SessionMessage.ID.make("msg_cancelled_queue")
- yield* session.prompt({
- id: inputID,
- sessionID,
- text: "Queue this",
- delivery: "queue",
- resume: false,
- })
- yield* session.cancelPending({ sessionID, inputID })
- expect(yield* session.pending(sessionID)).toEqual([])
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputCancelled.type, 1))).toBe(1)
- expect(
- yield* session.cancelPending({ sessionID, inputID }).pipe(Effect.flip),
- ).toMatchObject({ _tag: "Session.PendingInputConflictError", sessionID, inputID })
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputCancelled.type, 1))).toBe(1)
- const retried = yield* session.prompt({
- id: inputID,
- sessionID,
- text: "Queue this",
- delivery: "queue",
- resume: false,
- })
- expect(retried).toMatchObject({ id: inputID, delivery: "queue" })
- }),
- )
- it.effect("moves pending input between steer and queue delivery", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* Session.Service
- const queued = yield* session.synthetic({
- sessionID,
- text: "Steer this",
- delivery: "queue",
- resume: false,
- })
- const alreadySteered = yield* session.prompt({ sessionID, text: "Already steer", resume: false })
- wakeCalls.length = 0
- yield* session.steerPending({ sessionID, inputID: queued.id })
- expect(yield* session.pending(sessionID)).toMatchObject([
- { id: queued.id, delivery: "steer" },
- { id: alreadySteered.id, delivery: "steer" },
- ])
- expect(wakeCalls).toEqual([sessionID])
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputSteered.type, 1))).toBe(1)
- wakeCalls.length = 0
- yield* session.queuePending({ sessionID, inputID: queued.id })
- expect(yield* session.pending(sessionID)).toMatchObject([
- { id: queued.id, delivery: "queue" },
- { id: alreadySteered.id, delivery: "steer" },
- ])
- expect(wakeCalls).toEqual([])
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputQueued.type, 1))).toBe(1)
- expect(
- yield* session.steerPending({ sessionID, inputID: alreadySteered.id }).pipe(Effect.flip),
- ).toMatchObject({ _tag: "Session.PendingInputConflictError", sessionID, inputID: alreadySteered.id })
- yield* session.cancelPending({ sessionID, inputID: alreadySteered.id })
- expect(wakeCalls).toEqual([])
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputSteered.type, 1))).toBe(1)
- expect(yield* eventCount(Bus.versionedType(SessionEvent.InputCancelled.type, 1))).toBe(1)
- }),
- )
- })
|