session-prompt.test.ts 19 KB

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