1
0

session-prompt.test.ts 18 KB

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