session-prompt.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import { describe, expect } from "bun:test"
  2. import { DateTime, Effect, Fiber, Layer, Stream } from "effect"
  3. import { Database } from "@opencode-ai/core/database/database"
  4. import { EventV2 } from "@opencode-ai/core/event"
  5. import { SessionEvent } from "@opencode-ai/core/session/event"
  6. import { Project } from "@opencode-ai/core/project"
  7. import { ProjectTable } from "@opencode-ai/core/project/sql"
  8. import { AbsolutePath } from "@opencode-ai/core/schema"
  9. import { SessionV2 } from "@opencode-ai/core/session"
  10. import { Prompt } from "@opencode-ai/core/session/prompt"
  11. import { SessionMessage } from "@opencode-ai/core/session/message"
  12. import { SessionProjector } from "@opencode-ai/core/session/projector"
  13. import { SessionExecution } from "@opencode-ai/core/session/execution"
  14. import { SessionInput } from "@opencode-ai/core/session/input"
  15. import { SessionInputTable, SessionTable } from "@opencode-ai/core/session/sql"
  16. import { SessionStore } from "@opencode-ai/core/session/store"
  17. import { testEffect } from "./lib/effect"
  18. const database = Database.layerFromPath(":memory:")
  19. const events = EventV2.layer.pipe(Layer.provide(database))
  20. const projector = SessionProjector.layer.pipe(Layer.provide(events), Layer.provide(database))
  21. const store = SessionStore.layer.pipe(Layer.provide(database))
  22. const executionCalls: SessionV2.ID[] = []
  23. const wakeCalls: SessionV2.ID[] = []
  24. const execution = Layer.succeed(
  25. SessionExecution.Service,
  26. SessionExecution.Service.of({
  27. resume: (sessionID) =>
  28. Effect.sync(() => {
  29. executionCalls.push(sessionID)
  30. }),
  31. wake: (sessionID) =>
  32. Effect.sync(() => {
  33. wakeCalls.push(sessionID)
  34. }),
  35. }),
  36. )
  37. const sessions = SessionV2.layer.pipe(
  38. Layer.provide(events),
  39. Layer.provide(database),
  40. Layer.provide(store),
  41. Layer.provide(Project.defaultLayer),
  42. Layer.provide(execution),
  43. )
  44. const it = testEffect(Layer.mergeAll(database, events, projector, store, execution, sessions))
  45. const sessionID = SessionV2.ID.make("ses_prompt_test")
  46. const messageID = SessionMessage.ID.create()
  47. const setup = Effect.gen(function* () {
  48. const { db } = yield* Database.Service
  49. yield* db
  50. .insert(ProjectTable)
  51. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  52. .onConflictDoNothing()
  53. .run()
  54. .pipe(Effect.orDie)
  55. yield* db
  56. .insert(SessionTable)
  57. .values({
  58. id: sessionID,
  59. project_id: Project.ID.global,
  60. slug: "test",
  61. directory: "/project",
  62. title: "test",
  63. version: "test",
  64. })
  65. .onConflictDoNothing()
  66. .run()
  67. .pipe(Effect.orDie)
  68. })
  69. const admitted = (id: SessionMessage.ID) => Database.Service.use(({ db }) => SessionInput.find(db, id))
  70. const admittedCount = Database.Service.use(({ db }) =>
  71. db
  72. .select()
  73. .from(SessionInputTable)
  74. .all()
  75. .pipe(
  76. Effect.orDie,
  77. Effect.map((rows) => rows.length),
  78. ),
  79. )
  80. describe("SessionV2.prompt", () => {
  81. it.effect("delegates execution continuation through SessionExecution", () =>
  82. Effect.gen(function* () {
  83. yield* setup
  84. const session = yield* SessionV2.Service
  85. executionCalls.length = 0
  86. wakeCalls.length = 0
  87. yield* session.resume(sessionID)
  88. expect(executionCalls).toEqual([sessionID])
  89. expect(wakeCalls).toEqual([])
  90. }),
  91. )
  92. it.effect("durably admits one user message before transcript promotion", () =>
  93. Effect.gen(function* () {
  94. yield* setup
  95. const session = yield* SessionV2.Service
  96. const message = yield* session.prompt({
  97. sessionID,
  98. prompt: new Prompt({ text: "Fix the failing tests" }),
  99. resume: false,
  100. })
  101. expect(message.type).toBe("user")
  102. expect(message.text).toBe("Fix the failing tests")
  103. expect(yield* session.messages({ sessionID })).toEqual([])
  104. expect(yield* admitted(message.id)).toMatchObject({
  105. id: message.id,
  106. sessionID,
  107. prompt: { text: "Fix the failing tests" },
  108. delivery: "steer",
  109. })
  110. }),
  111. )
  112. it.effect("streams durable Session events after an aggregate cursor", () =>
  113. Effect.gen(function* () {
  114. yield* setup
  115. const session = yield* SessionV2.Service
  116. const events = yield* EventV2.Service
  117. const { db } = yield* Database.Service
  118. const fiber = yield* session.events({ sessionID }).pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped)
  119. yield* Effect.yieldNow
  120. yield* session.prompt({ sessionID, prompt: new Prompt({ text: "First" }), resume: false })
  121. yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Second" }), resume: false })
  122. yield* SessionInput.promoteSteers(db, events, sessionID)
  123. const streamed = Array.from(yield* Fiber.join(fiber))
  124. expect(
  125. streamed.map((event) => [event.cursor, event.event.type, (event.event.data as { prompt: Prompt }).prompt.text]),
  126. ).toEqual([
  127. [EventV2.Cursor.make(0), "session.next.prompted", "First"],
  128. [EventV2.Cursor.make(1), "session.next.prompted", "Second"],
  129. ])
  130. expect(
  131. Array.from(
  132. yield* session.events({ sessionID, after: streamed[0]!.cursor }).pipe(Stream.take(1), Stream.runCollect),
  133. ).map((event) => [event.cursor, (event.event.data as { prompt: Prompt }).prompt.text]),
  134. ).toEqual([[EventV2.Cursor.make(1), "Second"]])
  135. }),
  136. )
  137. it.effect("resumes through a recorded message without appending another prompt", () =>
  138. Effect.gen(function* () {
  139. yield* setup
  140. const session = yield* SessionV2.Service
  141. const message = yield* session.prompt({
  142. sessionID,
  143. prompt: new Prompt({ text: "Fix the failing tests" }),
  144. resume: false,
  145. })
  146. executionCalls.length = 0
  147. wakeCalls.length = 0
  148. yield* session.resume(sessionID)
  149. expect(yield* session.messages({ sessionID })).toEqual([])
  150. expect(yield* admitted(message.id)).not.toHaveProperty("promotedSeq")
  151. expect(executionCalls).toEqual([sessionID])
  152. expect(wakeCalls).toEqual([])
  153. }),
  154. )
  155. it.effect("records distinct messages when the ID is omitted", () =>
  156. Effect.gen(function* () {
  157. yield* setup
  158. const session = yield* SessionV2.Service
  159. const input = { sessionID, prompt: new Prompt({ text: "Fix the failing tests" }), resume: false }
  160. const first = yield* session.prompt(input)
  161. const second = yield* session.prompt(input)
  162. expect(second.id).not.toBe(first.id)
  163. expect(yield* session.messages({ sessionID })).toEqual([])
  164. expect(yield* admittedCount).toBe(2)
  165. }),
  166. )
  167. it.effect("returns the original recorded message when the ID is retried", () =>
  168. Effect.gen(function* () {
  169. yield* setup
  170. const session = yield* SessionV2.Service
  171. const input = {
  172. sessionID,
  173. id: messageID,
  174. prompt: new Prompt({ text: "Fix the failing tests" }),
  175. resume: false,
  176. }
  177. const first = yield* session.prompt(input)
  178. const retried = yield* session.prompt(input)
  179. expect(retried).toEqual(first)
  180. expect(yield* session.messages({ sessionID })).toEqual([])
  181. expect(yield* admittedCount).toBe(1)
  182. }),
  183. )
  184. it.effect("wakes execution when an exact prompt retry recovers a committed message", () =>
  185. Effect.gen(function* () {
  186. yield* setup
  187. const session = yield* SessionV2.Service
  188. const input = {
  189. sessionID,
  190. id: messageID,
  191. prompt: new Prompt({ text: "Recover committed prompt" }),
  192. resume: false,
  193. }
  194. const first = yield* session.prompt(input)
  195. wakeCalls.length = 0
  196. const retried = yield* session.prompt({ ...input, resume: true })
  197. expect(retried).toEqual(first)
  198. expect(wakeCalls).toEqual([sessionID])
  199. }),
  200. )
  201. it.effect("rejects reuse of one ID with a different prompt", () =>
  202. Effect.gen(function* () {
  203. yield* setup
  204. const session = yield* SessionV2.Service
  205. yield* session.prompt({
  206. sessionID,
  207. id: messageID,
  208. prompt: new Prompt({ text: "Fix the failing tests" }),
  209. })
  210. const failure = yield* session
  211. .prompt({
  212. sessionID,
  213. id: messageID,
  214. prompt: new Prompt({ text: "Delete the failing tests" }),
  215. resume: false,
  216. })
  217. .pipe(Effect.flip)
  218. expect(failure._tag).toBe("Session.PromptConflictError")
  219. expect(yield* session.messages({ sessionID })).toHaveLength(0)
  220. expect(yield* admittedCount).toBe(1)
  221. }),
  222. )
  223. it.effect("rejects reuse of one ID with a different delivery mode", () =>
  224. Effect.gen(function* () {
  225. yield* setup
  226. const session = yield* SessionV2.Service
  227. yield* session.prompt({
  228. id: messageID,
  229. sessionID,
  230. prompt: new Prompt({ text: "Fix the failing tests" }),
  231. resume: false,
  232. })
  233. const failure = yield* session
  234. .prompt({
  235. id: messageID,
  236. sessionID,
  237. prompt: new Prompt({ text: "Fix the failing tests" }),
  238. delivery: "queue",
  239. resume: false,
  240. })
  241. .pipe(Effect.flip)
  242. expect(failure._tag).toBe("Session.PromptConflictError")
  243. }),
  244. )
  245. it.effect("does not match pending inputs when no delivery modes are eligible", () =>
  246. Effect.gen(function* () {
  247. yield* setup
  248. const { db } = yield* Database.Service
  249. const session = yield* SessionV2.Service
  250. yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Wait" }), resume: false })
  251. expect(yield* SessionInput.hasPending(db, sessionID, [])).toBe(false)
  252. }),
  253. )
  254. it.effect("returns one recorded message to concurrent exact retries", () =>
  255. Effect.gen(function* () {
  256. yield* setup
  257. const session = yield* SessionV2.Service
  258. const input = {
  259. sessionID,
  260. id: messageID,
  261. prompt: new Prompt({ text: "Fix the failing tests" }),
  262. resume: false,
  263. }
  264. const messages = yield* Effect.all([session.prompt(input), session.prompt(input)], { concurrency: "unbounded" })
  265. expect(messages[1]).toEqual(messages[0])
  266. expect(yield* session.messages({ sessionID })).toEqual([])
  267. expect(yield* admittedCount).toBe(1)
  268. }),
  269. )
  270. it.effect("reconciles an existing projected prompt into a promoted inbox record", () =>
  271. Effect.gen(function* () {
  272. yield* setup
  273. const session = yield* SessionV2.Service
  274. const events = yield* EventV2.Service
  275. const prompt = new Prompt({ text: "Historical prompt" })
  276. yield* events.publish(
  277. SessionEvent.Prompted,
  278. { sessionID, timestamp: yield* DateTime.now, prompt, delivery: "steer" },
  279. { id: messageID },
  280. )
  281. const retried = yield* session.prompt({ id: messageID, sessionID, prompt, resume: false })
  282. expect(retried).toMatchObject({ id: messageID, text: "Historical prompt" })
  283. expect(yield* admitted(messageID)).toHaveProperty("promotedSeq")
  284. }),
  285. )
  286. it.effect("reconciles an existing projected queued prompt with its delivery mode", () =>
  287. Effect.gen(function* () {
  288. yield* setup
  289. const session = yield* SessionV2.Service
  290. const events = yield* EventV2.Service
  291. const prompt = new Prompt({ text: "Historical queued prompt" })
  292. yield* events.publish(
  293. SessionEvent.Prompted,
  294. { sessionID, timestamp: yield* DateTime.now, prompt, delivery: "queue" },
  295. { id: messageID },
  296. )
  297. const retried = yield* session.prompt({ id: messageID, sessionID, prompt, delivery: "queue", resume: false })
  298. expect(retried).toMatchObject({ id: messageID, text: "Historical queued prompt" })
  299. expect(yield* admitted(messageID)).toMatchObject({ delivery: "queue" })
  300. }),
  301. )
  302. it.effect("rejects an input ID already used by a durable non-prompt event", () =>
  303. Effect.gen(function* () {
  304. yield* setup
  305. const session = yield* SessionV2.Service
  306. const events = yield* EventV2.Service
  307. yield* events.publish(
  308. SessionEvent.Synthetic,
  309. { sessionID, timestamp: yield* DateTime.now, text: "Collision" },
  310. { id: messageID },
  311. )
  312. const failure = yield* session
  313. .prompt({ id: messageID, sessionID, prompt: new Prompt({ text: "Collision" }), resume: false })
  314. .pipe(Effect.flip)
  315. expect(failure._tag).toBe("Session.PromptConflictError")
  316. expect(yield* admitted(messageID)).toBeUndefined()
  317. }),
  318. )
  319. it.effect("rejects a durable event ID reserved by an admitted prompt without poisoning promotion", () =>
  320. Effect.gen(function* () {
  321. yield* setup
  322. const { db } = yield* Database.Service
  323. const session = yield* SessionV2.Service
  324. const events = yield* EventV2.Service
  325. const prompt = new Prompt({ text: "Reserved prompt" })
  326. yield* session.prompt({ id: messageID, sessionID, prompt, resume: false })
  327. const failure = yield* events
  328. .publish(
  329. SessionEvent.Synthetic,
  330. { sessionID, timestamp: yield* DateTime.now, text: "Conflicting synthetic" },
  331. { id: messageID },
  332. )
  333. .pipe(Effect.catchDefect(Effect.succeed))
  334. expect(failure).toBe("Durable event conflicts with admitted prompt input")
  335. expect(yield* admitted(messageID)).not.toHaveProperty("promotedSeq")
  336. expect(yield* session.messages({ sessionID })).toEqual([])
  337. yield* SessionInput.promoteSteers(db, events, sessionID)
  338. expect(yield* admitted(messageID)).toMatchObject({ promotedSeq: 0 })
  339. expect(yield* session.messages({ sessionID })).toMatchObject([
  340. { id: messageID, type: "user", text: "Reserved prompt" },
  341. ])
  342. }),
  343. )
  344. it.effect("rejects reuse of one globally unique message ID across sessions", () =>
  345. Effect.gen(function* () {
  346. yield* setup
  347. const { db } = yield* Database.Service
  348. const session = yield* SessionV2.Service
  349. const other = SessionV2.ID.make("ses_prompt_other")
  350. yield* db
  351. .insert(SessionTable)
  352. .values({
  353. id: other,
  354. project_id: Project.ID.global,
  355. slug: "other",
  356. directory: "/project",
  357. title: "other",
  358. version: "test",
  359. })
  360. .onConflictDoNothing()
  361. .run()
  362. .pipe(Effect.orDie)
  363. const prompt = new Prompt({ text: "Fix the failing tests" })
  364. yield* session.prompt({ id: messageID, sessionID, prompt, resume: false })
  365. const failure = yield* session
  366. .prompt({ id: messageID, sessionID: other, prompt, resume: false })
  367. .pipe(Effect.flip)
  368. expect(failure).toMatchObject({ _tag: "Session.PromptConflictError", sessionID: other, messageID })
  369. }),
  370. )
  371. it.effect("starts execution by default after recording the prompt", () =>
  372. Effect.gen(function* () {
  373. yield* setup
  374. const session = yield* SessionV2.Service
  375. executionCalls.length = 0
  376. wakeCalls.length = 0
  377. yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Run by default" }) })
  378. expect(executionCalls).toEqual([])
  379. expect(wakeCalls).toEqual([sessionID])
  380. }),
  381. )
  382. it.effect("starts execution when resume is explicitly true", () =>
  383. Effect.gen(function* () {
  384. yield* setup
  385. const session = yield* SessionV2.Service
  386. executionCalls.length = 0
  387. wakeCalls.length = 0
  388. yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Run explicitly" }), resume: true })
  389. expect(executionCalls).toEqual([])
  390. expect(wakeCalls).toEqual([sessionID])
  391. }),
  392. )
  393. it.effect("only records the prompt when resume is false", () =>
  394. Effect.gen(function* () {
  395. yield* setup
  396. const session = yield* SessionV2.Service
  397. executionCalls.length = 0
  398. wakeCalls.length = 0
  399. yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Do not run" }), resume: false })
  400. expect(executionCalls).toEqual([])
  401. expect(wakeCalls).toEqual([])
  402. }),
  403. )
  404. })