session-projector.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. import { describe, expect } from "bun:test"
  2. import { DateTime, Effect, Fiber, Option, Schema, Stream } from "effect"
  3. import { asc, eq, sql } from "drizzle-orm"
  4. import { Database } from "@opencode-ai/core/database/database"
  5. import { Agent } from "@opencode-ai/core/agent"
  6. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  7. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  8. import { Bus } from "@opencode-ai/core/bus"
  9. import { Event } from "@opencode-ai/schema/event"
  10. import { EventTable } from "@opencode-ai/core/event/sql"
  11. import { Model } from "@opencode-ai/core/model"
  12. import { Project } from "@opencode-ai/core/project"
  13. import { ProjectTable } from "@opencode-ai/core/project/sql"
  14. import { Provider } from "@opencode-ai/core/provider"
  15. import { AbsolutePath } from "@opencode-ai/core/schema"
  16. import { Session } from "@opencode-ai/core/session"
  17. import { SessionEvent } from "@opencode-ai/core/session/event"
  18. import { SessionMessage } from "@opencode-ai/core/session/message"
  19. import { Money } from "@opencode-ai/schema/money"
  20. import { SessionProjector } from "@opencode-ai/core/session/projector"
  21. import { SessionExecution } from "@opencode-ai/core/session/execution"
  22. import { fromRow } from "@opencode-ai/core/session/info"
  23. import { SessionPending } from "@opencode-ai/core/session/pending"
  24. import { Shell } from "@opencode-ai/schema/shell"
  25. import {
  26. InstructionStateTable,
  27. SessionPendingTable,
  28. SessionMessageTable,
  29. SessionTable,
  30. } from "@opencode-ai/core/session/sql"
  31. import { testEffect } from "./lib/effect"
  32. import { Snapshot } from "@opencode-ai/core/snapshot"
  33. const it = testEffect(
  34. AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, SessionProjector.node]), [
  35. [Bus.node, Bus.configured({ persist: true })],
  36. ]),
  37. )
  38. const sessionsLayer = AppNodeBuilder.build(Session.node, [[SessionExecution.node, SessionExecution.noopLayer]])
  39. const sessionID = Session.ID.make("ses_projector_test")
  40. const created = DateTime.makeUnsafe(0)
  41. const model = { id: Model.ID.make("model"), providerID: Provider.ID.make("provider") }
  42. const previousModel = { ...model, variant: Model.VariantID.make("medium") }
  43. const encodeMessage = Schema.encodeSync(SessionMessage.Info)
  44. const build = Agent.defaultID
  45. const assistantRow = (
  46. id: SessionMessage.ID,
  47. seq: number,
  48. time: { created: DateTime.Utc; completed?: DateTime.Utc } = { created },
  49. usage?: Pick<SessionMessage.Assistant, "cost" | "tokens">,
  50. ) => {
  51. const {
  52. id: _,
  53. type,
  54. ...data
  55. } = encodeMessage(
  56. SessionMessage.Assistant.make({ id, type: "assistant", agent: build, model, content: [], time, ...usage }),
  57. )
  58. return { id, session_id: sessionID, type, seq, time_created: DateTime.toEpochMillis(time.created), data }
  59. }
  60. describe("SessionProjector", () => {
  61. it.effect("does not settle a pending manual compaction on an auto failure", () =>
  62. Effect.gen(function* () {
  63. const db = (yield* Database.Service).db
  64. yield* db
  65. .insert(ProjectTable)
  66. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  67. .run()
  68. yield* db
  69. .insert(SessionTable)
  70. .values({
  71. id: sessionID,
  72. project_id: Project.ID.global,
  73. slug: "test",
  74. directory: "/project",
  75. title: "test",
  76. version: "test",
  77. })
  78. .run()
  79. const bus = yield* Bus.Service
  80. const inputID = SessionMessage.ID.make("msg_manual_compaction")
  81. yield* SessionPending.admitCompaction(db, bus, { id: inputID, sessionID })
  82. yield* bus.publish(SessionEvent.Compaction.Failed, {
  83. sessionID,
  84. reason: "auto",
  85. error: { type: "compaction.failed", message: "Auto compaction failed" },
  86. })
  87. expect(yield* SessionPending.compaction(db, sessionID)).toMatchObject({ id: inputID })
  88. }),
  89. )
  90. it.effect("loads legacy revert storage into canonical state", () =>
  91. Effect.gen(function* () {
  92. const db = (yield* Database.Service).db
  93. yield* db
  94. .insert(ProjectTable)
  95. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  96. .run()
  97. yield* db
  98. .insert(SessionTable)
  99. .values({
  100. id: sessionID,
  101. project_id: Project.ID.global,
  102. slug: "test",
  103. directory: "/project",
  104. title: "test",
  105. version: "test",
  106. })
  107. .run()
  108. const legacy = JSON.stringify({
  109. messageID: "msg_boundary",
  110. snapshot: "tree",
  111. diff: "legacy patch",
  112. files: [{ path: "src/old.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" }],
  113. })
  114. yield* db.run(sql`update session_v2 set revert = ${legacy} where id = ${sessionID}`)
  115. const stored = yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get()
  116. if (!stored) return yield* Effect.die("Session row missing")
  117. const storedRevert = fromRow(stored).revert
  118. expect(String(storedRevert?.messageID)).toBe("msg_boundary")
  119. expect(String(storedRevert?.snapshot)).toBe("tree")
  120. expect(storedRevert?.files).toEqual([
  121. { file: "src/old.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" },
  122. ])
  123. }),
  124. )
  125. it.effect("projects staged, cleared, and committed reverts", () =>
  126. Effect.gen(function* () {
  127. const db = (yield* Database.Service).db
  128. yield* db
  129. .insert(ProjectTable)
  130. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  131. .run()
  132. yield* db
  133. .insert(SessionTable)
  134. .values({
  135. id: sessionID,
  136. project_id: Project.ID.global,
  137. slug: "test",
  138. directory: "/project",
  139. title: "test",
  140. version: "test",
  141. cost: 1.25,
  142. tokens_input: 10,
  143. tokens_output: 4,
  144. tokens_reasoning: 2,
  145. tokens_cache_read: 3,
  146. tokens_cache_write: 1,
  147. })
  148. .run()
  149. const boundary = SessionMessage.ID.make("msg_boundary")
  150. const earlier = SessionMessage.ID.make("msg_earlier")
  151. yield* db
  152. .insert(SessionMessageTable)
  153. .values([
  154. assistantRow(earlier, 0),
  155. assistantRow(
  156. boundary,
  157. 1,
  158. { created },
  159. {
  160. cost: Money.USD.make(0.5),
  161. tokens: { input: 4, output: 1, reasoning: 1, cache: { read: 1, write: 0 } },
  162. },
  163. ),
  164. assistantRow(
  165. SessionMessage.ID.make("msg_later"),
  166. 2,
  167. { created },
  168. {
  169. cost: Money.USD.make(0.75),
  170. tokens: { input: 6, output: 3, reasoning: 1, cache: { read: 2, write: 1 } },
  171. },
  172. ),
  173. ])
  174. .run()
  175. yield* db
  176. .insert(InstructionStateTable)
  177. .values({
  178. session_id: sessionID,
  179. epoch_start: 0,
  180. through_seq: 0,
  181. initial_values: {},
  182. current_values: {},
  183. })
  184. .run()
  185. const bus = yield* Bus.Service
  186. yield* bus.publish(SessionEvent.RevertEvent.Staged, {
  187. sessionID,
  188. revert: { messageID: boundary, snapshot: Snapshot.ID.make("tree"), files: [] },
  189. })
  190. expect((yield* db.select({ revert: SessionTable.revert }).from(SessionTable).get())?.revert).toMatchObject({
  191. messageID: boundary,
  192. snapshot: "tree",
  193. files: [],
  194. })
  195. yield* bus.publish(SessionEvent.RevertEvent.Cleared, { sessionID })
  196. expect((yield* db.select({ revert: SessionTable.revert }).from(SessionTable).get())?.revert).toBeNull()
  197. yield* bus.publish(SessionEvent.RevertEvent.Staged, {
  198. sessionID,
  199. revert: { messageID: boundary, files: [] },
  200. })
  201. yield* bus.publish(SessionEvent.RevertEvent.Committed, {
  202. sessionID,
  203. to: boundary,
  204. })
  205. expect(
  206. (yield* db.select({ id: SessionMessageTable.id }).from(SessionMessageTable).all()).map((row) => row.id),
  207. ).toEqual([earlier])
  208. expect(yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get()).toMatchObject({
  209. cost: Money.USD.make(1.25),
  210. tokens_input: 10,
  211. tokens_output: 4,
  212. tokens_reasoning: 2,
  213. tokens_cache_read: 3,
  214. tokens_cache_write: 1,
  215. })
  216. // A committed revert resets the fold cache so the next boundary establishes a new epoch.
  217. expect(yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)).toBeUndefined()
  218. }),
  219. )
  220. it.effect("orders projected messages and context by durable aggregate sequence", () =>
  221. Effect.gen(function* () {
  222. const { db } = yield* Database.Service
  223. yield* db
  224. .insert(ProjectTable)
  225. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  226. .run()
  227. .pipe(Effect.orDie)
  228. yield* db
  229. .insert(SessionTable)
  230. .values({
  231. id: sessionID,
  232. project_id: Project.ID.global,
  233. slug: "test",
  234. directory: "/project",
  235. title: "test",
  236. version: "test",
  237. })
  238. .run()
  239. .pipe(Effect.orDie)
  240. const bus = yield* Bus.Service
  241. yield* bus.publish(SessionEvent.InputAdmitted, {
  242. sessionID,
  243. inputID: SessionMessage.ID.make("msg_first"),
  244. input: { type: "user", data: { text: "first" }, delivery: "steer" },
  245. })
  246. yield* bus.publish(
  247. SessionEvent.InputPromoted,
  248. {
  249. sessionID,
  250. inputID: SessionMessage.ID.make("msg_first"),
  251. },
  252. { id: Event.ID.make("evt_z") },
  253. )
  254. yield* bus.publish(SessionEvent.InputAdmitted, {
  255. sessionID,
  256. inputID: SessionMessage.ID.make("msg_second"),
  257. input: { type: "user", data: { text: "second" }, delivery: "steer" },
  258. })
  259. yield* bus.publish(
  260. SessionEvent.InputPromoted,
  261. {
  262. sessionID,
  263. inputID: SessionMessage.ID.make("msg_second"),
  264. },
  265. { id: Event.ID.make("evt_a") },
  266. )
  267. const sessions = yield* Session.Service
  268. const firstPage = yield* sessions.messages({ sessionID, limit: 1, order: "asc" })
  269. expect(firstPage.map((message) => (message.type === "user" ? message.text : message.type))).toEqual(["first"])
  270. const secondPage = yield* sessions.messages({
  271. sessionID,
  272. limit: 1,
  273. order: "asc",
  274. cursor: { id: firstPage[0]!.id, direction: "next" },
  275. })
  276. expect(secondPage.map((message) => (message.type === "user" ? message.text : message.type))).toEqual(["second"])
  277. expect(
  278. (yield* sessions.messages({
  279. sessionID,
  280. limit: 1,
  281. order: "asc",
  282. cursor: { id: secondPage[0]!.id, direction: "previous" },
  283. })).map((message) => (message.type === "user" ? message.text : message.type)),
  284. ).toEqual(["first"])
  285. expect(
  286. (yield* sessions.context(sessionID)).map((message) => (message.type === "user" ? message.text : message.type)),
  287. ).toEqual(["first", "second"])
  288. }).pipe(Effect.provide(sessionsLayer)),
  289. )
  290. it.effect("consumes the pending row and projects the message at promotion", () =>
  291. Effect.gen(function* () {
  292. const { db } = yield* Database.Service
  293. yield* db
  294. .insert(ProjectTable)
  295. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  296. .run()
  297. .pipe(Effect.orDie)
  298. yield* db
  299. .insert(SessionTable)
  300. .values({
  301. id: sessionID,
  302. project_id: Project.ID.global,
  303. slug: "test",
  304. directory: "/project",
  305. title: "test",
  306. version: "test",
  307. })
  308. .run()
  309. .pipe(Effect.orDie)
  310. const bus = yield* Bus.Service
  311. const id = SessionMessage.ID.make("msg_admitted")
  312. const admitted = yield* SessionPending.admit(db, bus, {
  313. id,
  314. sessionID,
  315. input: { type: "user", data: { text: "promote me" }, delivery: "steer" },
  316. })
  317. if (!admitted) return yield* Effect.die("Prompt admission failed")
  318. const event = yield* bus.publish(SessionEvent.InputPromoted, {
  319. sessionID,
  320. inputID: id,
  321. })
  322. expect(
  323. yield* db.select().from(SessionPendingTable).where(eq(SessionPendingTable.id, id)).get().pipe(Effect.orDie),
  324. ).toBeUndefined()
  325. expect(
  326. yield* db.select().from(SessionMessageTable).where(eq(SessionMessageTable.id, id)).get().pipe(Effect.orDie),
  327. ).toMatchObject({ session_id: sessionID, type: "user", seq: event.durable?.seq })
  328. }),
  329. )
  330. it.effect("projects durable context messages supported by the updater", () =>
  331. Effect.gen(function* () {
  332. const { db } = yield* Database.Service
  333. yield* db
  334. .insert(ProjectTable)
  335. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  336. .run()
  337. .pipe(Effect.orDie)
  338. yield* db
  339. .insert(SessionTable)
  340. .values({
  341. id: sessionID,
  342. project_id: Project.ID.global,
  343. slug: "test",
  344. directory: "/project",
  345. title: "test",
  346. version: "test",
  347. model: previousModel,
  348. })
  349. .run()
  350. .pipe(Effect.orDie)
  351. const bus = yield* Bus.Service
  352. yield* bus.publish(SessionEvent.AgentSelected, {
  353. sessionID,
  354. agent: build,
  355. })
  356. yield* bus.publish(SessionEvent.ModelSelected, {
  357. sessionID,
  358. model,
  359. })
  360. yield* bus.publish(SessionEvent.Synthetic, {
  361. sessionID,
  362. text: "synthetic context",
  363. metadata: { source: "projector-test" },
  364. })
  365. yield* bus.publish(SessionEvent.Shell.Started, {
  366. sessionID,
  367. shell: Shell.Info.make({
  368. id: Shell.ID.make("sh_projector"),
  369. status: "running",
  370. command: "pwd",
  371. cwd: "/project",
  372. shell: "/bin/sh",
  373. file: "/tmp/sh_projector.out",
  374. metadata: {},
  375. time: { started: 0 },
  376. }),
  377. })
  378. yield* bus.publish(SessionEvent.Shell.Ended, {
  379. sessionID,
  380. shell: Shell.Info.make({
  381. id: Shell.ID.make("sh_projector"),
  382. status: "exited",
  383. command: "pwd",
  384. cwd: "/project",
  385. shell: "/bin/sh",
  386. file: "/tmp/sh_projector.out",
  387. exit: 0,
  388. metadata: {},
  389. time: { started: 0, completed: 1 },
  390. }),
  391. output: { output: "/project", cursor: 8, size: 8, truncated: false },
  392. })
  393. yield* bus.publish(SessionEvent.Compaction.Started, {
  394. sessionID,
  395. reason: "manual",
  396. recent: "recent context",
  397. })
  398. yield* bus.publish(SessionEvent.Compaction.Delta, {
  399. sessionID,
  400. text: "partial",
  401. })
  402. expect(
  403. yield* db
  404. .select({ id: EventTable.id })
  405. .from(EventTable)
  406. .where(sql`${EventTable.type} like 'session.compaction.delta.%'`)
  407. .all()
  408. .pipe(Effect.orDie),
  409. ).toHaveLength(0)
  410. expect(
  411. yield* db
  412. .select({ data: SessionMessageTable.data })
  413. .from(SessionMessageTable)
  414. .where(eq(SessionMessageTable.type, "compaction"))
  415. .all()
  416. .pipe(Effect.orDie),
  417. ).toEqual([{ data: expect.objectContaining({ status: "running", summary: "", recent: "recent context" }) }])
  418. yield* bus.publish(SessionEvent.Compaction.Ended, {
  419. sessionID,
  420. reason: "manual",
  421. text: "summary",
  422. recent: "recent context",
  423. })
  424. const rows = yield* db
  425. .select()
  426. .from(SessionMessageTable)
  427. .where(eq(SessionMessageTable.session_id, sessionID))
  428. .orderBy(asc(SessionMessageTable.seq))
  429. .all()
  430. .pipe(Effect.orDie)
  431. const messages = rows.map((row) =>
  432. Schema.decodeUnknownSync(SessionMessage.Info)({ ...row.data, id: row.id, type: row.type }),
  433. )
  434. expect(messages.map((message) => message.type)).toEqual([
  435. "agent-switched",
  436. "model-switched",
  437. "synthetic",
  438. "shell",
  439. "compaction",
  440. ])
  441. expect(messages.find((message) => message.type === "synthetic")).toMatchObject({
  442. text: "synthetic context",
  443. metadata: { source: "projector-test" },
  444. })
  445. expect(messages.find((message) => message.type === "model-switched")).toMatchObject({ previous: previousModel })
  446. expect(messages.find((message) => message.type === "shell")).toMatchObject({
  447. command: "pwd",
  448. status: "exited",
  449. exit: 0,
  450. output: { output: "/project", truncated: false },
  451. time: { completed: DateTime.makeUnsafe(0) },
  452. })
  453. expect(messages.find((message) => message.type === "compaction")).toMatchObject({
  454. summary: "summary",
  455. recent: "recent context",
  456. })
  457. expect(
  458. yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie),
  459. ).toMatchObject({
  460. agent: "build",
  461. model,
  462. time_updated: DateTime.toEpochMillis(created),
  463. })
  464. }),
  465. )
  466. it.effect("rejects distinct creator events that reuse one projected message ID", () =>
  467. Effect.gen(function* () {
  468. const { db } = yield* Database.Service
  469. yield* db
  470. .insert(ProjectTable)
  471. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  472. .run()
  473. .pipe(Effect.orDie)
  474. yield* db
  475. .insert(SessionTable)
  476. .values({
  477. id: sessionID,
  478. project_id: Project.ID.global,
  479. slug: "test",
  480. directory: "/project",
  481. title: "test",
  482. version: "test",
  483. })
  484. .run()
  485. .pipe(Effect.orDie)
  486. const bus = yield* Bus.Service
  487. const id = SessionMessage.ID.make("msg_creator_collision")
  488. const { id: _, type, ...data } = encodeMessage({ id, type: "synthetic", text: "existing", time: { created } })
  489. yield* db
  490. .insert(SessionMessageTable)
  491. .values({ id, session_id: sessionID, type, seq: 0, time_created: 0, data })
  492. .run()
  493. const exit = yield* bus
  494. .publish(SessionEvent.Step.Started, {
  495. sessionID,
  496. assistantMessageID: id,
  497. agent: build,
  498. model,
  499. })
  500. .pipe(Effect.exit)
  501. expect(exit._tag).toBe("Failure")
  502. expect(
  503. yield* db.select().from(SessionMessageTable).where(eq(SessionMessageTable.id, id)).get().pipe(Effect.orDie),
  504. ).toMatchObject({ type: "synthetic" })
  505. }),
  506. )
  507. it.effect("projects retry state and clears it at the next step or execution terminal", () =>
  508. Effect.gen(function* () {
  509. const { db } = yield* Database.Service
  510. yield* db
  511. .insert(ProjectTable)
  512. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  513. .run()
  514. .pipe(Effect.orDie)
  515. yield* db
  516. .insert(SessionTable)
  517. .values({
  518. id: sessionID,
  519. project_id: Project.ID.global,
  520. slug: "test",
  521. directory: "/project",
  522. title: "test",
  523. version: "test",
  524. })
  525. .run()
  526. .pipe(Effect.orDie)
  527. const bus = yield* Bus.Service
  528. const first = SessionMessage.ID.make("msg_retry_first")
  529. const second = SessionMessage.ID.make("msg_retry_second")
  530. yield* bus.publish(SessionEvent.Step.Started, { sessionID, assistantMessageID: first, agent: build, model })
  531. yield* bus.publish(SessionEvent.RetryScheduled, {
  532. sessionID,
  533. assistantMessageID: first,
  534. attempt: 2,
  535. at: 2_000,
  536. error: { type: "provider.transport", message: "Disconnected" },
  537. })
  538. const decode = (row: typeof SessionMessageTable.$inferSelect) =>
  539. Schema.decodeUnknownSync(SessionMessage.Info)({ ...row.data, id: row.id, type: row.type })
  540. const firstRow = yield* db
  541. .select()
  542. .from(SessionMessageTable)
  543. .where(eq(SessionMessageTable.id, first))
  544. .get()
  545. .pipe(Effect.orDie)
  546. const projected = firstRow ?? (yield* Effect.die(new Error("Missing retry projection")))
  547. expect(decode(projected)).toMatchObject({
  548. retry: { attempt: 2, at: DateTime.makeUnsafe(2_000), error: { type: "provider.transport" } },
  549. })
  550. yield* bus.publish(SessionEvent.Step.Started, { sessionID, assistantMessageID: second, agent: build, model })
  551. yield* bus.publish(SessionEvent.RetryScheduled, {
  552. sessionID,
  553. assistantMessageID: second,
  554. attempt: 3,
  555. at: 6_000,
  556. error: { type: "provider.internal", message: "Unavailable" },
  557. })
  558. yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID, reason: "shutdown" })
  559. const rows = yield* db
  560. .select()
  561. .from(SessionMessageTable)
  562. .where(eq(SessionMessageTable.session_id, sessionID))
  563. .orderBy(asc(SessionMessageTable.seq))
  564. .all()
  565. .pipe(Effect.orDie)
  566. expect(decode(rows[0])).not.toHaveProperty("retry")
  567. expect(decode(rows[1])).not.toHaveProperty("retry")
  568. }),
  569. )
  570. it.effect("does not infer restart continuation from lifecycle history", () =>
  571. Effect.gen(function* () {
  572. const { db } = yield* Database.Service
  573. yield* db
  574. .insert(ProjectTable)
  575. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  576. .run()
  577. .pipe(Effect.orDie)
  578. yield* db
  579. .insert(SessionTable)
  580. .values({
  581. id: sessionID,
  582. project_id: Project.ID.global,
  583. slug: "test",
  584. directory: "/project",
  585. title: "test",
  586. version: "test",
  587. })
  588. .run()
  589. .pipe(Effect.orDie)
  590. const bus = yield* Bus.Service
  591. const suspended = () =>
  592. db
  593. .select({ timeSuspended: SessionTable.time_suspended })
  594. .from(SessionTable)
  595. .where(eq(SessionTable.id, sessionID))
  596. .get()
  597. .pipe(Effect.orDie)
  598. yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID, reason: "shutdown" })
  599. expect((yield* suspended())?.timeSuspended).toBeNull()
  600. yield* bus.publish(SessionEvent.Execution.Started, { sessionID })
  601. expect((yield* suspended())?.timeSuspended).toBeNull()
  602. }),
  603. )
  604. it.effect("updates only the newest incomplete assistant projection", () =>
  605. Effect.gen(function* () {
  606. const { db } = yield* Database.Service
  607. yield* db
  608. .insert(ProjectTable)
  609. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  610. .run()
  611. .pipe(Effect.orDie)
  612. yield* db
  613. .insert(SessionTable)
  614. .values({
  615. id: sessionID,
  616. project_id: Project.ID.global,
  617. slug: "test",
  618. directory: "/project",
  619. title: "test",
  620. version: "test",
  621. })
  622. .run()
  623. .pipe(Effect.orDie)
  624. yield* db
  625. .insert(SessionMessageTable)
  626. .values([
  627. assistantRow(SessionMessage.ID.make("msg_assistant_1"), 0),
  628. assistantRow(SessionMessage.ID.make("msg_assistant_2"), 1),
  629. ])
  630. .run()
  631. .pipe(Effect.orDie)
  632. const service = yield* Bus.Service
  633. const usageUpdated = yield* service
  634. .subscribe(SessionEvent.UsageUpdated)
  635. .pipe(Stream.runHead, Effect.forkScoped({ startImmediately: true }))
  636. yield* service.publish(SessionEvent.Step.Ended, {
  637. sessionID,
  638. assistantMessageID: SessionMessage.ID.make("msg_assistant_2"),
  639. finish: "stop",
  640. cost: Money.USD.make(1.25),
  641. tokens: { input: 10, output: 4, reasoning: 2, cache: { read: 3, write: 1 } },
  642. })
  643. const rows = yield* db
  644. .select()
  645. .from(SessionMessageTable)
  646. .where(eq(SessionMessageTable.session_id, sessionID))
  647. .orderBy(asc(SessionMessageTable.id))
  648. .all()
  649. .pipe(Effect.orDie)
  650. const messages = rows.map((row) =>
  651. Schema.decodeUnknownSync(SessionMessage.Info)({ ...row.data, id: row.id, type: row.type }),
  652. )
  653. expect(messages[0]).not.toHaveProperty("time.completed")
  654. expect(messages[1]).toMatchObject({
  655. type: "assistant",
  656. finish: "stop",
  657. cost: Money.USD.make(1.25),
  658. tokens: { input: 10, output: 4, reasoning: 2, cache: { read: 3, write: 1 } },
  659. time: { completed: DateTime.makeUnsafe(0) },
  660. })
  661. expect(
  662. yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie),
  663. ).toMatchObject({
  664. cost: 1.25,
  665. tokens_input: 10,
  666. tokens_output: 4,
  667. tokens_reasoning: 2,
  668. tokens_cache_read: 3,
  669. tokens_cache_write: 1,
  670. })
  671. expect(Option.getOrThrow(yield* Fiber.join(usageUpdated)).data).toEqual({
  672. sessionID,
  673. cost: Money.USD.make(1.25),
  674. tokens: { input: 10, output: 4, reasoning: 2, cache: { read: 3, write: 1 } },
  675. })
  676. }),
  677. )
  678. it.effect("does not revive a stale incomplete assistant projection", () =>
  679. Effect.gen(function* () {
  680. const { db } = yield* Database.Service
  681. yield* db
  682. .insert(ProjectTable)
  683. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  684. .run()
  685. .pipe(Effect.orDie)
  686. yield* db
  687. .insert(SessionTable)
  688. .values({
  689. id: sessionID,
  690. project_id: Project.ID.global,
  691. slug: "test",
  692. directory: "/project",
  693. title: "test",
  694. version: "test",
  695. })
  696. .run()
  697. .pipe(Effect.orDie)
  698. yield* db
  699. .insert(SessionMessageTable)
  700. .values([
  701. assistantRow(SessionMessage.ID.make("msg_assistant_stale"), 0),
  702. assistantRow(SessionMessage.ID.make("msg_assistant_completed"), 1, {
  703. created: DateTime.makeUnsafe(1),
  704. completed: DateTime.makeUnsafe(2),
  705. }),
  706. ])
  707. .run()
  708. .pipe(Effect.orDie)
  709. const service = yield* Bus.Service
  710. yield* service.publish(SessionEvent.Text.Started, {
  711. sessionID,
  712. assistantMessageID: SessionMessage.ID.make("msg_assistant_completed"),
  713. ordinal: 0,
  714. })
  715. const rows = yield* db
  716. .select()
  717. .from(SessionMessageTable)
  718. .where(eq(SessionMessageTable.session_id, sessionID))
  719. .orderBy(asc(SessionMessageTable.id))
  720. .all()
  721. .pipe(Effect.orDie)
  722. const messages = rows.map((row) =>
  723. Schema.decodeUnknownSync(SessionMessage.Info)({ ...row.data, id: row.id, type: row.type }),
  724. )
  725. expect(messages).toEqual([
  726. SessionMessage.Assistant.make({
  727. id: SessionMessage.ID.make("msg_assistant_completed"),
  728. type: "assistant",
  729. agent: build,
  730. model,
  731. content: [SessionMessage.AssistantText.make({ type: "text", text: "" })],
  732. time: { created: DateTime.makeUnsafe(1), completed: DateTime.makeUnsafe(2) },
  733. }),
  734. SessionMessage.Assistant.make({
  735. id: SessionMessage.ID.make("msg_assistant_stale"),
  736. type: "assistant",
  737. agent: build,
  738. model,
  739. content: [],
  740. time: { created },
  741. }),
  742. ])
  743. }),
  744. )
  745. })