session-projector.test.ts 18 KB

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