session-prompt.test.ts 19 KB

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