session-projector.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import { describe, expect } from "bun:test"
  2. import { DateTime, Effect, Layer, Schema } from "effect"
  3. import { asc, 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 { ModelV2 } from "@opencode-ai/core/model"
  8. import { Project } from "@opencode-ai/core/project"
  9. import { ProjectTable } from "@opencode-ai/core/project/sql"
  10. import { ProviderV2 } from "@opencode-ai/core/provider"
  11. import { AbsolutePath } from "@opencode-ai/core/schema"
  12. import { SessionV2 } from "@opencode-ai/core/session"
  13. import { SessionEvent } from "@opencode-ai/core/session/event"
  14. import { SessionMessage } from "@opencode-ai/core/session/message"
  15. import { Prompt } from "@opencode-ai/core/session/prompt"
  16. import { SessionMessageUpdater } from "@opencode-ai/core/session/message-updater"
  17. import { SessionProjector } from "@opencode-ai/core/session/projector"
  18. import { SessionExecution } from "@opencode-ai/core/session/execution"
  19. import { SessionInput } from "@opencode-ai/core/session/input"
  20. import { SessionStore } from "@opencode-ai/core/session/store"
  21. import { SessionInputTable, SessionMessageTable, SessionTable } from "@opencode-ai/core/session/sql"
  22. import { testEffect } from "./lib/effect"
  23. const it = testEffect(Layer.mergeAll(Database.defaultLayer, EventV2.defaultLayer, SessionProjector.defaultLayer))
  24. const sessionID = SessionV2.ID.make("ses_projector_test")
  25. const created = DateTime.makeUnsafe(0)
  26. const model = { id: ModelV2.ID.make("model"), providerID: ProviderV2.ID.make("provider") }
  27. const encodeMessage = Schema.encodeSync(SessionMessage.Message)
  28. const assistantRow = (
  29. id: SessionMessage.ID,
  30. seq: number,
  31. time: { created: DateTime.Utc; completed?: DateTime.Utc } = { created },
  32. ) => {
  33. const {
  34. id: _,
  35. type,
  36. ...data
  37. } = encodeMessage(new SessionMessage.Assistant({ id, type: "assistant", agent: "build", model, content: [], time }))
  38. return { id, session_id: sessionID, type, seq, time_created: DateTime.toEpochMillis(time.created), data }
  39. }
  40. describe("SessionProjector", () => {
  41. it.effect("orders projected messages and context by durable aggregate sequence", () =>
  42. Effect.gen(function* () {
  43. const { db } = yield* Database.Service
  44. yield* db
  45. .insert(ProjectTable)
  46. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  47. .run()
  48. .pipe(Effect.orDie)
  49. yield* db
  50. .insert(SessionTable)
  51. .values({
  52. id: sessionID,
  53. project_id: Project.ID.global,
  54. slug: "test",
  55. directory: "/project",
  56. title: "test",
  57. version: "test",
  58. })
  59. .run()
  60. .pipe(Effect.orDie)
  61. const events = yield* EventV2.Service
  62. yield* events.publish(
  63. SessionEvent.Prompted,
  64. {
  65. sessionID,
  66. messageID: SessionMessage.ID.make("msg_first"),
  67. timestamp: created,
  68. prompt: new Prompt({ text: "first" }),
  69. delivery: "steer",
  70. },
  71. { id: EventV2.ID.make("evt_z") },
  72. )
  73. yield* events.publish(
  74. SessionEvent.Prompted,
  75. {
  76. sessionID,
  77. messageID: SessionMessage.ID.make("msg_second"),
  78. timestamp: created,
  79. prompt: new Prompt({ text: "second" }),
  80. delivery: "steer",
  81. },
  82. { id: EventV2.ID.make("evt_a") },
  83. )
  84. const sessions = yield* SessionV2.Service
  85. const firstPage = yield* sessions.messages({ sessionID, limit: 1, order: "asc" })
  86. expect(firstPage.map((message) => (message.type === "user" ? message.text : message.type))).toEqual(["first"])
  87. const secondPage = yield* sessions.messages({
  88. sessionID,
  89. limit: 1,
  90. order: "asc",
  91. cursor: { id: firstPage[0]!.id, direction: "next" },
  92. })
  93. expect(secondPage.map((message) => (message.type === "user" ? message.text : message.type))).toEqual(["second"])
  94. expect(
  95. (yield* sessions.messages({
  96. sessionID,
  97. limit: 1,
  98. order: "asc",
  99. cursor: { id: secondPage[0]!.id, direction: "previous" },
  100. })).map((message) => (message.type === "user" ? message.text : message.type)),
  101. ).toEqual(["first"])
  102. expect(
  103. (yield* sessions.context(sessionID)).map((message) => (message.type === "user" ? message.text : message.type)),
  104. ).toEqual(["first", "second"])
  105. }).pipe(
  106. Effect.provide(
  107. SessionV2.layer.pipe(
  108. Layer.provide(EventV2.defaultLayer),
  109. Layer.provide(Database.defaultLayer),
  110. Layer.provide(Project.defaultLayer),
  111. Layer.provide(SessionStore.defaultLayer),
  112. Layer.provide(SessionExecution.noopLayer),
  113. ),
  114. ),
  115. ),
  116. )
  117. it.effect("marks an admitted lifecycle row promoted with the PromptPromoted event sequence", () =>
  118. Effect.gen(function* () {
  119. const { db } = yield* Database.Service
  120. yield* db
  121. .insert(ProjectTable)
  122. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  123. .run()
  124. .pipe(Effect.orDie)
  125. yield* db
  126. .insert(SessionTable)
  127. .values({
  128. id: sessionID,
  129. project_id: Project.ID.global,
  130. slug: "test",
  131. directory: "/project",
  132. title: "test",
  133. version: "test",
  134. })
  135. .run()
  136. .pipe(Effect.orDie)
  137. const events = yield* EventV2.Service
  138. const id = SessionMessage.ID.make("msg_admitted")
  139. yield* SessionInput.admit(db, events, {
  140. id,
  141. sessionID,
  142. prompt: new Prompt({ text: "promote me" }),
  143. delivery: "steer",
  144. })
  145. const event = yield* events.publish(SessionEvent.PromptLifecycle.Promoted, {
  146. sessionID,
  147. timestamp: created,
  148. messageID: id,
  149. prompt: new Prompt({ text: "promote me" }),
  150. timeCreated: created,
  151. })
  152. expect(
  153. yield* db.select().from(SessionInputTable).where(eq(SessionInputTable.id, id)).get().pipe(Effect.orDie),
  154. ).toMatchObject({ promoted_seq: event.durable?.seq })
  155. }),
  156. )
  157. it.effect("projects durable context messages supported by the updater", () =>
  158. Effect.gen(function* () {
  159. const { db } = yield* Database.Service
  160. yield* db
  161. .insert(ProjectTable)
  162. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  163. .run()
  164. .pipe(Effect.orDie)
  165. yield* db
  166. .insert(SessionTable)
  167. .values({
  168. id: sessionID,
  169. project_id: Project.ID.global,
  170. slug: "test",
  171. directory: "/project",
  172. title: "test",
  173. version: "test",
  174. })
  175. .run()
  176. .pipe(Effect.orDie)
  177. const events = yield* EventV2.Service
  178. yield* events.publish(SessionEvent.AgentSwitched, {
  179. sessionID,
  180. messageID: SessionMessage.ID.create(),
  181. timestamp: created,
  182. agent: "build",
  183. })
  184. yield* events.publish(SessionEvent.ModelSwitched, {
  185. sessionID,
  186. messageID: SessionMessage.ID.create(),
  187. timestamp: created,
  188. model,
  189. })
  190. yield* events.publish(SessionEvent.Synthetic, {
  191. sessionID,
  192. messageID: SessionMessage.ID.create(),
  193. timestamp: created,
  194. text: "synthetic context",
  195. })
  196. yield* events.publish(SessionEvent.Shell.Started, {
  197. sessionID,
  198. messageID: SessionMessage.ID.create(),
  199. timestamp: created,
  200. callID: "shell-1",
  201. command: "pwd",
  202. })
  203. yield* events.publish(SessionEvent.Shell.Ended, {
  204. sessionID,
  205. timestamp: DateTime.makeUnsafe(1),
  206. callID: "shell-1",
  207. output: "/project",
  208. })
  209. const compactionID = SessionMessage.ID.create()
  210. yield* events.publish(SessionEvent.Compaction.Started, {
  211. sessionID,
  212. messageID: compactionID,
  213. timestamp: created,
  214. reason: "manual",
  215. })
  216. yield* events.publish(SessionEvent.Compaction.Delta, {
  217. sessionID,
  218. messageID: compactionID,
  219. timestamp: created,
  220. text: "partial",
  221. })
  222. expect(
  223. yield* db
  224. .select({ id: EventTable.id })
  225. .from(EventTable)
  226. .where(eq(EventTable.type, SessionEvent.Compaction.Delta.type))
  227. .all()
  228. .pipe(Effect.orDie),
  229. ).toEqual([])
  230. expect(
  231. yield* db
  232. .select({ id: SessionMessageTable.id })
  233. .from(SessionMessageTable)
  234. .where(eq(SessionMessageTable.type, "compaction"))
  235. .all()
  236. .pipe(Effect.orDie),
  237. ).toEqual([])
  238. yield* events.publish(SessionEvent.Compaction.Ended, {
  239. sessionID,
  240. messageID: compactionID,
  241. timestamp: DateTime.makeUnsafe(1),
  242. reason: "manual",
  243. text: "summary",
  244. recent: "recent context",
  245. })
  246. const rows = yield* db
  247. .select()
  248. .from(SessionMessageTable)
  249. .where(eq(SessionMessageTable.session_id, sessionID))
  250. .orderBy(asc(SessionMessageTable.seq))
  251. .all()
  252. .pipe(Effect.orDie)
  253. const messages = rows.map((row) =>
  254. Schema.decodeUnknownSync(SessionMessage.Message)({ ...row.data, id: row.id, type: row.type }),
  255. )
  256. expect(messages.map((message) => message.type)).toEqual([
  257. "agent-switched",
  258. "model-switched",
  259. "synthetic",
  260. "shell",
  261. "compaction",
  262. ])
  263. expect(messages.find((message) => message.type === "shell")).toMatchObject({
  264. output: "/project",
  265. time: { completed: DateTime.makeUnsafe(1) },
  266. })
  267. expect(messages.find((message) => message.type === "compaction")).toMatchObject({
  268. summary: "summary",
  269. recent: "recent context",
  270. })
  271. expect(
  272. yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie),
  273. ).toMatchObject({
  274. agent: "build",
  275. model,
  276. time_updated: DateTime.toEpochMillis(created),
  277. })
  278. }),
  279. )
  280. it.effect("rejects distinct creator events that reuse one projected message ID", () =>
  281. Effect.gen(function* () {
  282. const { db } = yield* Database.Service
  283. yield* db
  284. .insert(ProjectTable)
  285. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  286. .run()
  287. .pipe(Effect.orDie)
  288. yield* db
  289. .insert(SessionTable)
  290. .values({
  291. id: sessionID,
  292. project_id: Project.ID.global,
  293. slug: "test",
  294. directory: "/project",
  295. title: "test",
  296. version: "test",
  297. })
  298. .run()
  299. .pipe(Effect.orDie)
  300. const events = yield* EventV2.Service
  301. const id = SessionMessage.ID.make("msg_creator_collision")
  302. yield* events.publish(SessionEvent.Synthetic, { sessionID, messageID: id, timestamp: created, text: "keep me" })
  303. const exit = yield* events
  304. .publish(SessionEvent.Step.Started, {
  305. sessionID,
  306. assistantMessageID: id,
  307. timestamp: created,
  308. agent: "build",
  309. model,
  310. })
  311. .pipe(Effect.exit)
  312. expect(exit._tag).toBe("Failure")
  313. expect(
  314. yield* db.select().from(SessionMessageTable).where(eq(SessionMessageTable.id, id)).get().pipe(Effect.orDie),
  315. ).toMatchObject({ type: "synthetic" })
  316. }),
  317. )
  318. it.effect("does not revive a stale incomplete in-memory assistant projection", () =>
  319. Effect.gen(function* () {
  320. const stale = new SessionMessage.Assistant({
  321. id: SessionMessage.ID.make("msg_assistant_stale"),
  322. type: "assistant",
  323. agent: "build",
  324. model,
  325. content: [],
  326. time: { created },
  327. })
  328. const completed = new SessionMessage.Assistant({
  329. id: SessionMessage.ID.make("msg_assistant_completed"),
  330. type: "assistant",
  331. agent: "build",
  332. model,
  333. content: [],
  334. time: { created: DateTime.makeUnsafe(1), completed: DateTime.makeUnsafe(2) },
  335. })
  336. expect(
  337. yield* SessionMessageUpdater.memory({ messages: [stale, completed] }).getCurrentAssistant(),
  338. ).toBeUndefined()
  339. }),
  340. )
  341. it.effect("updates only the newest incomplete assistant projection", () =>
  342. Effect.gen(function* () {
  343. const { db } = yield* Database.Service
  344. yield* db
  345. .insert(ProjectTable)
  346. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  347. .run()
  348. .pipe(Effect.orDie)
  349. yield* db
  350. .insert(SessionTable)
  351. .values({
  352. id: sessionID,
  353. project_id: Project.ID.global,
  354. slug: "test",
  355. directory: "/project",
  356. title: "test",
  357. version: "test",
  358. })
  359. .run()
  360. .pipe(Effect.orDie)
  361. yield* db
  362. .insert(SessionMessageTable)
  363. .values([
  364. assistantRow(SessionMessage.ID.make("msg_assistant_1"), 0),
  365. assistantRow(SessionMessage.ID.make("msg_assistant_2"), 1),
  366. ])
  367. .run()
  368. .pipe(Effect.orDie)
  369. const service = yield* EventV2.Service
  370. yield* service.publish(SessionEvent.Step.Ended, {
  371. sessionID,
  372. timestamp: DateTime.makeUnsafe(1),
  373. assistantMessageID: SessionMessage.ID.make("msg_assistant_2"),
  374. finish: "stop",
  375. cost: 0,
  376. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  377. })
  378. const rows = yield* db
  379. .select()
  380. .from(SessionMessageTable)
  381. .where(eq(SessionMessageTable.session_id, sessionID))
  382. .orderBy(asc(SessionMessageTable.id))
  383. .all()
  384. .pipe(Effect.orDie)
  385. const messages = rows.map((row) =>
  386. Schema.decodeUnknownSync(SessionMessage.Message)({ ...row.data, id: row.id, type: row.type }),
  387. )
  388. expect(messages[0]).not.toHaveProperty("time.completed")
  389. expect(messages[1]).toMatchObject({
  390. type: "assistant",
  391. finish: "stop",
  392. time: { completed: DateTime.makeUnsafe(1) },
  393. })
  394. }),
  395. )
  396. it.effect("does not revive a stale incomplete assistant projection", () =>
  397. Effect.gen(function* () {
  398. const { db } = yield* Database.Service
  399. yield* db
  400. .insert(ProjectTable)
  401. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  402. .run()
  403. .pipe(Effect.orDie)
  404. yield* db
  405. .insert(SessionTable)
  406. .values({
  407. id: sessionID,
  408. project_id: Project.ID.global,
  409. slug: "test",
  410. directory: "/project",
  411. title: "test",
  412. version: "test",
  413. })
  414. .run()
  415. .pipe(Effect.orDie)
  416. yield* db
  417. .insert(SessionMessageTable)
  418. .values([
  419. assistantRow(SessionMessage.ID.make("msg_assistant_stale"), 0),
  420. assistantRow(SessionMessage.ID.make("msg_assistant_completed"), 1, {
  421. created: DateTime.makeUnsafe(1),
  422. completed: DateTime.makeUnsafe(2),
  423. }),
  424. ])
  425. .run()
  426. .pipe(Effect.orDie)
  427. const service = yield* EventV2.Service
  428. yield* service.publish(SessionEvent.Text.Started, {
  429. sessionID,
  430. assistantMessageID: SessionMessage.ID.make("msg_assistant_completed"),
  431. timestamp: DateTime.makeUnsafe(3),
  432. textID: "text-stale",
  433. })
  434. const rows = yield* db
  435. .select()
  436. .from(SessionMessageTable)
  437. .where(eq(SessionMessageTable.session_id, sessionID))
  438. .orderBy(asc(SessionMessageTable.id))
  439. .all()
  440. .pipe(Effect.orDie)
  441. const messages = rows.map((row) =>
  442. Schema.decodeUnknownSync(SessionMessage.Message)({ ...row.data, id: row.id, type: row.type }),
  443. )
  444. expect(messages).toEqual([
  445. new SessionMessage.Assistant({
  446. id: SessionMessage.ID.make("msg_assistant_completed"),
  447. type: "assistant",
  448. agent: "build",
  449. model,
  450. content: [new SessionMessage.AssistantText({ type: "text", id: "text-stale", text: "" })],
  451. time: { created: DateTime.makeUnsafe(1), completed: DateTime.makeUnsafe(2) },
  452. }),
  453. new SessionMessage.Assistant({
  454. id: SessionMessage.ID.make("msg_assistant_stale"),
  455. type: "assistant",
  456. agent: "build",
  457. model,
  458. content: [],
  459. time: { created },
  460. }),
  461. ])
  462. }),
  463. )
  464. })