session-prompt.test.ts 19 KB

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