session-prompt.test.ts 18 KB

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