session-create.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import { describe, expect } from "bun:test"
  2. import path from "path"
  3. import { DateTime, Effect, Layer, Stream } from "effect"
  4. import { AgentV2 } from "@opencode-ai/core/agent"
  5. import { asc, eq } from "drizzle-orm"
  6. import { Database } from "@opencode-ai/core/database/database"
  7. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  8. import { LayerNode } from "@opencode-ai/core/effect/layer-node"
  9. import { EventV2 } from "@opencode-ai/core/event"
  10. import { EventTable } from "@opencode-ai/core/event/sql"
  11. import { Job } from "@opencode-ai/core/job"
  12. import { Location } from "@opencode-ai/core/location"
  13. import { ModelV2 } from "@opencode-ai/core/model"
  14. import { ProjectV2 } from "@opencode-ai/core/project"
  15. import { ProjectTable } from "@opencode-ai/core/project/sql"
  16. import { ProviderV2 } from "@opencode-ai/core/provider"
  17. import { AbsolutePath } from "@opencode-ai/core/schema"
  18. import { SessionV2 } from "@opencode-ai/core/session"
  19. import { SessionV1 } from "@opencode-ai/core/v1/session"
  20. import { Prompt } from "@opencode-ai/core/session/prompt"
  21. import { SessionProjector } from "@opencode-ai/core/session/projector"
  22. import { SessionExecution } from "@opencode-ai/core/session/execution"
  23. import { SessionInput } from "@opencode-ai/core/session/input"
  24. import { SessionEvent } from "@opencode-ai/core/session/event"
  25. import { SessionMessage } from "@opencode-ai/core/session/message"
  26. import { SessionTable } from "@opencode-ai/core/session/sql"
  27. import { SessionStore } from "@opencode-ai/core/session/store"
  28. import { WorkspaceV2 } from "@opencode-ai/core/workspace"
  29. import { testEffect } from "./lib/effect"
  30. import { tmpdir } from "./fixture/tmpdir"
  31. const projects = Layer.succeed(
  32. ProjectV2.Service,
  33. ProjectV2.Service.of({
  34. resolve: (directory) => Effect.succeed({ id: ProjectV2.ID.global, directory }),
  35. directories: () => Effect.succeed([]),
  36. commit: () => Effect.void,
  37. }),
  38. )
  39. const it = testEffect(
  40. AppNodeBuilder.build(
  41. LayerNode.group([Database.node, EventV2.node, SessionProjector.node, SessionStore.node, SessionV2.node]),
  42. [
  43. [ProjectV2.node, projects],
  44. [SessionExecution.node, SessionExecution.noopLayer],
  45. ],
  46. ),
  47. )
  48. const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
  49. const id = SessionV2.ID.create()
  50. /** Public session events from a `log` read, without caught-up markers. */
  51. const logEvents = (session: SessionV2.Interface, sessionID: SessionV2.ID, follow?: boolean) =>
  52. session
  53. .log({ sessionID, follow })
  54. .pipe(Stream.filter((item): item is SessionEvent.DurableEvent => !EventV2.isCaughtUp(item)))
  55. const assertCreateInputTypes = (session: SessionV2.Interface) => {
  56. // @ts-expect-error location or parentID is required.
  57. session.create({})
  58. // @ts-expect-error child sessions inherit their parent's location.
  59. session.create({ parentID: SessionV2.ID.create(), location })
  60. }
  61. void assertCreateInputTypes
  62. describe("SessionV2.create", () => {
  63. it.effect("creates a fresh projected session when the ID is omitted", () =>
  64. Effect.gen(function* () {
  65. const session = yield* SessionV2.Service
  66. const first = yield* session.create({ location })
  67. const second = yield* session.create({ location })
  68. expect(second.id).not.toBe(first.id)
  69. expect((yield* session.list()).data).toHaveLength(2)
  70. }),
  71. )
  72. it.effect("returns the original session when the ID is retried", () =>
  73. Effect.gen(function* () {
  74. const session = yield* SessionV2.Service
  75. const input = { id, location }
  76. const first = yield* session.create(input)
  77. const retried = yield* session.create(input)
  78. expect(retried).toEqual(first)
  79. expect((yield* session.list()).data).toEqual([first])
  80. }),
  81. )
  82. it.effect("stores supplied immutable create attributes", () =>
  83. Effect.gen(function* () {
  84. const session = yield* SessionV2.Service
  85. const workspaceID = WorkspaceV2.ID.make("wrk_test")
  86. const model = ModelV2.Ref.make({
  87. id: ModelV2.ID.make("sonnet"),
  88. providerID: ProviderV2.ID.anthropic,
  89. variant: ModelV2.VariantID.make("fast"),
  90. })
  91. expect(
  92. yield* session.create({
  93. location: Location.Ref.make({ directory: location.directory, workspaceID }),
  94. agent: AgentV2.ID.make("build"),
  95. model,
  96. }),
  97. ).toMatchObject({ location: { directory: location.directory, workspaceID }, agent: "build", model })
  98. }),
  99. )
  100. it.effect("inherits location from an existing parent when omitted", () =>
  101. Effect.gen(function* () {
  102. const session = yield* SessionV2.Service
  103. const parent = yield* session.create({ location })
  104. const child = yield* session.create({ parentID: parent.id, title: "child" })
  105. expect(child).toMatchObject({ parentID: parent.id, location })
  106. }),
  107. )
  108. it.effect("rejects child creation when the parent does not exist", () =>
  109. Effect.gen(function* () {
  110. const session = yield* SessionV2.Service
  111. const missing = SessionV2.ID.create()
  112. expect(yield* Effect.flip(session.create({ parentID: missing, title: "child" }))).toEqual(
  113. new SessionV2.NotFoundError({ sessionID: missing }),
  114. )
  115. }),
  116. )
  117. it.effect("forks a session by replaying a durable fork event into copied projected rows", () =>
  118. Effect.gen(function* () {
  119. const session = yield* SessionV2.Service
  120. const events = yield* EventV2.Service
  121. const { db } = yield* Database.Service
  122. const parent = yield* session.create({ location, title: "Parent" })
  123. const admitted = yield* session.prompt({
  124. sessionID: parent.id,
  125. prompt: Prompt.make({ text: "First" }),
  126. resume: false,
  127. })
  128. yield* SessionInput.promoteSteers(db, events, parent.id, Number.MAX_SAFE_INTEGER)
  129. yield* events.publish(SessionEvent.Synthetic, {
  130. sessionID: parent.id,
  131. messageID: SessionMessage.ID.create(),
  132. timestamp: yield* DateTime.now,
  133. text: "parent note",
  134. })
  135. const forked = yield* session.fork({ sessionID: parent.id })
  136. const parentContext = yield* session.context(parent.id)
  137. const forkContext = yield* session.context(forked.id)
  138. const history = Array.from(yield* Stream.runCollect(logEvents(session, forked.id)))
  139. expect(forked).toMatchObject({ parentID: parent.id, title: "Parent (fork #1)" })
  140. expect(forkContext).toMatchObject([
  141. { type: "user", text: "First" },
  142. { type: "synthetic", text: "parent note", sessionID: forked.id },
  143. ])
  144. expect(forkContext.map((message) => message.id)).not.toEqual(parentContext.map((message) => message.id))
  145. expect(history).toHaveLength(1)
  146. expect(history[0]).toMatchObject({
  147. type: "session.next.forked",
  148. durable: { seq: 0 },
  149. data: { sessionID: forked.id, parentID: parent.id },
  150. })
  151. expect(yield* SessionInput.find(db, forkContext[0]!.id)).toMatchObject({
  152. sessionID: forked.id,
  153. prompt: { text: "First" },
  154. promotedSeq: 2,
  155. })
  156. yield* session.prompt({ sessionID: parent.id, prompt: Prompt.make({ text: "Parent changed" }), resume: false })
  157. yield* SessionInput.promoteSteers(db, events, parent.id, Number.MAX_SAFE_INTEGER)
  158. yield* session.prompt({ sessionID: forked.id, prompt: Prompt.make({ text: "Child continues" }), resume: false })
  159. yield* SessionInput.promoteSteers(db, events, forked.id, Number.MAX_SAFE_INTEGER)
  160. expect((yield* session.context(parent.id)).map((message) => message.type)).toEqual(["user", "synthetic", "user"])
  161. expect((yield* session.context(forked.id)).map((message) => message.type)).toEqual(["user", "synthetic", "user"])
  162. expect((yield* session.context(forked.id)).at(-1)).toMatchObject({ text: "Child continues" })
  163. expect(
  164. Array.from(yield* Stream.runCollect(logEvents(session, forked.id))).map(
  165. (event): number | undefined => event.durable?.seq,
  166. ),
  167. ).toEqual([0, 4, 5])
  168. expect(yield* SessionInput.find(db, admitted.id)).toMatchObject({ sessionID: parent.id })
  169. }),
  170. )
  171. it.effect("forks before the selected boundary message", () =>
  172. Effect.gen(function* () {
  173. const session = yield* SessionV2.Service
  174. const events = yield* EventV2.Service
  175. const { db } = yield* Database.Service
  176. const parent = yield* session.create({ location })
  177. const first = yield* session.prompt({
  178. sessionID: parent.id,
  179. prompt: Prompt.make({ text: "First" }),
  180. resume: false,
  181. })
  182. yield* SessionInput.promoteSteers(db, events, parent.id, Number.MAX_SAFE_INTEGER)
  183. const second = yield* session.prompt({
  184. sessionID: parent.id,
  185. prompt: Prompt.make({ text: "Second" }),
  186. resume: false,
  187. })
  188. yield* SessionInput.promoteSteers(db, events, parent.id, Number.MAX_SAFE_INTEGER)
  189. const forked = yield* session.fork({ sessionID: parent.id, messageID: second.id })
  190. const context = yield* session.context(forked.id)
  191. const history = Array.from(yield* Stream.runCollect(logEvents(session, forked.id)))
  192. expect(context).toMatchObject([{ text: "First" }])
  193. expect(context[0]?.id).not.toBe(first.id)
  194. expect(history[0]).toMatchObject({ data: { messageID: second.id } })
  195. }),
  196. )
  197. it.effect("returns the existing Session when one ID is reused with different create arguments", () =>
  198. Effect.gen(function* () {
  199. const session = yield* SessionV2.Service
  200. const created = yield* session.create({ id, location })
  201. const changed = [
  202. { id, location: Location.Ref.make({ directory: AbsolutePath.make("/other") }) },
  203. { id, location, agent: AgentV2.ID.make("build") },
  204. {
  205. id,
  206. location,
  207. model: ModelV2.Ref.make({ id: ModelV2.ID.make("sonnet"), providerID: ProviderV2.ID.anthropic }),
  208. },
  209. ]
  210. for (const input of changed) {
  211. expect(yield* session.create(input)).toEqual(created)
  212. }
  213. expect((yield* session.list()).data).toHaveLength(1)
  214. }),
  215. )
  216. it.effect("returns one recorded session to concurrent exact retries", () =>
  217. Effect.gen(function* () {
  218. const session = yield* SessionV2.Service
  219. const input = { id, location }
  220. const created = yield* Effect.all([session.create(input), session.create(input)], { concurrency: "unbounded" })
  221. expect(created[1]).toEqual(created[0])
  222. expect((yield* session.list()).data).toEqual([created[0]])
  223. }),
  224. )
  225. it.effect("returns the current Session projection after updates", () =>
  226. Effect.gen(function* () {
  227. const session = yield* SessionV2.Service
  228. const { db } = yield* Database.Service
  229. const input = { id, location }
  230. const created = yield* session.create(input)
  231. yield* db.update(SessionTable).set({ agent: "build" }).where(eq(SessionTable.id, id)).run().pipe(Effect.orDie)
  232. expect(yield* session.create(input)).toMatchObject({ id: created.id, agent: "build" })
  233. }),
  234. )
  235. it.effect("returns the current Session projection after projected updates", () =>
  236. Effect.gen(function* () {
  237. const session = yield* SessionV2.Service
  238. const events = yield* EventV2.Service
  239. const input = { id, location }
  240. const created = yield* session.create(input)
  241. yield* events.publish(SessionV1.Event.Updated, {
  242. sessionID: id,
  243. info: SessionV1.SessionInfo.make({
  244. id,
  245. slug: "updated",
  246. version: "test",
  247. projectID: created.projectID,
  248. directory: created.location.directory,
  249. title: "updated",
  250. agent: "build",
  251. time: { created: 0, updated: 1 },
  252. }),
  253. })
  254. expect(yield* session.create(input)).toMatchObject({ id, agent: "build" })
  255. }),
  256. )
  257. it.effect("persists creation through the existing legacy created event", () =>
  258. Effect.gen(function* () {
  259. const session = yield* SessionV2.Service
  260. const { db } = yield* Database.Service
  261. const created = yield* session.create({ location })
  262. expect(
  263. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).all().pipe(Effect.orDie),
  264. ).toMatchObject([{ type: EventV2.versionedType(SessionV1.Event.Created.type, 1) }])
  265. }),
  266. )
  267. it.effect("persists caller-ID creation through the existing created event", () =>
  268. Effect.gen(function* () {
  269. const session = yield* SessionV2.Service
  270. const { db } = yield* Database.Service
  271. const created = yield* session.create({ id, location })
  272. expect(
  273. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).get().pipe(Effect.orDie),
  274. ).toMatchObject({
  275. data: { sessionID: id },
  276. })
  277. }),
  278. )
  279. it.effect("omits legacy creation rows from the V2 Session event stream", () =>
  280. Effect.gen(function* () {
  281. const session = yield* SessionV2.Service
  282. const events = yield* EventV2.Service
  283. const { db } = yield* Database.Service
  284. const created = yield* session.create({ location })
  285. yield* session.prompt({ sessionID: created.id, prompt: Prompt.make({ text: "Hello" }), resume: false })
  286. yield* SessionInput.promoteSteers(db, events, created.id, Number.MAX_SAFE_INTEGER)
  287. expect(
  288. Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(2), Stream.runCollect)),
  289. ).toMatchObject([
  290. { durable: { seq: 1 }, type: "session.next.prompt.admitted", data: { prompt: { text: "Hello" } } },
  291. { durable: { seq: 2 }, type: "session.next.prompted" },
  292. ])
  293. }),
  294. )
  295. it.effect("replays one prompt lifecycle into a fresh target database", () =>
  296. Effect.gen(function* () {
  297. const session = yield* SessionV2.Service
  298. const sourceEvents = yield* EventV2.Service
  299. const sourceDb = (yield* Database.Service).db
  300. const created = yield* session.create({ id: SessionV2.ID.make("ses_fresh_target_replay"), location })
  301. const admitted = yield* session.prompt({
  302. sessionID: created.id,
  303. prompt: Prompt.make({ text: "Replay lifecycle" }),
  304. resume: false,
  305. })
  306. yield* SessionInput.promoteSteers(sourceDb, sourceEvents, created.id, Number.MAX_SAFE_INTEGER)
  307. const serialized = (yield* sourceDb
  308. .select()
  309. .from(EventTable)
  310. .where(eq(EventTable.aggregate_id, created.id))
  311. .orderBy(asc(EventTable.seq))
  312. .all()
  313. .pipe(Effect.orDie)).map((event) => ({
  314. id: event.id,
  315. aggregateID: event.aggregate_id,
  316. seq: event.seq,
  317. type: event.type,
  318. data: event.data,
  319. }))
  320. const tmp = yield* Effect.acquireRelease(
  321. Effect.promise(() => tmpdir()),
  322. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  323. )
  324. const targetDatabase = Database.layerFromPath(path.join(tmp.path, "target.sqlite"))
  325. const targetLayer = AppNodeBuilder.build(
  326. LayerNode.group([Database.node, EventV2.node, SessionProjector.node, SessionStore.node]),
  327. [[Database.node, targetDatabase]],
  328. )
  329. yield* Effect.gen(function* () {
  330. const db = (yield* Database.Service).db
  331. const events = yield* EventV2.Service
  332. const store = yield* SessionStore.Service
  333. yield* db
  334. .insert(ProjectTable)
  335. .values({ id: ProjectV2.ID.global, worktree: location.directory, sandboxes: [] })
  336. .run()
  337. .pipe(Effect.orDie)
  338. expect(yield* store.get(created.id)).toBeUndefined()
  339. expect(yield* events.replayAll(serialized.slice(0, 2))).toBe(created.id)
  340. expect(yield* SessionInput.find(db, admitted.id)).toMatchObject({
  341. id: admitted.id,
  342. sessionID: created.id,
  343. prompt: { text: "Replay lifecycle" },
  344. delivery: "steer",
  345. admittedSeq: 1,
  346. })
  347. expect(yield* store.context(created.id)).toEqual([])
  348. expect(yield* events.replayAll(serialized.slice(2))).toBe(created.id)
  349. expect(yield* SessionInput.find(db, admitted.id)).toMatchObject({
  350. id: admitted.id,
  351. sessionID: created.id,
  352. prompt: { text: "Replay lifecycle" },
  353. delivery: "steer",
  354. admittedSeq: 1,
  355. promotedSeq: 2,
  356. })
  357. expect(yield* store.context(created.id)).toMatchObject([
  358. { id: admitted.id, type: "user", text: "Replay lifecycle" },
  359. ])
  360. expect(
  361. (yield* db
  362. .select()
  363. .from(EventTable)
  364. .where(eq(EventTable.aggregate_id, created.id))
  365. .orderBy(asc(EventTable.seq))
  366. .all()
  367. .pipe(Effect.orDie)).map((event) => [event.seq, event.type]),
  368. ).toEqual([
  369. [0, EventV2.versionedType(SessionV1.Event.Created.type, 1)],
  370. [1, EventV2.versionedType(SessionEvent.PromptAdmitted.type, 1)],
  371. [2, EventV2.versionedType(SessionEvent.Prompted.type, 1)],
  372. ])
  373. }).pipe(Effect.provide(Layer.fresh(targetLayer)))
  374. }),
  375. )
  376. it.effect("does not mask unrelated created projector defects", () =>
  377. Effect.gen(function* () {
  378. const session = yield* SessionV2.Service
  379. const event = yield* EventV2.Service
  380. const defect = new Error("unrelated projector defect")
  381. yield* event.project(SessionV1.Event.Created, () => Effect.die(defect))
  382. expect(yield* session.create({ id, location }).pipe(Effect.catchDefect(Effect.succeed))).toBe(defect)
  383. }),
  384. )
  385. it.effect("reports unfinished Session operations as unavailable", () =>
  386. Effect.gen(function* () {
  387. const session = yield* SessionV2.Service
  388. const created = yield* session.create({ location })
  389. const unavailable = (
  390. effect: Effect.Effect<void, SessionV2.NotFoundError | SessionV2.OperationUnavailableError>,
  391. ) =>
  392. effect.pipe(
  393. Effect.flip,
  394. Effect.map((error) => (error instanceof SessionV2.OperationUnavailableError ? error.operation : "not-found")),
  395. )
  396. expect(yield* unavailable(session.shell({ sessionID: created.id, command: "pwd" }))).toBe("shell")
  397. }),
  398. )
  399. it.effect("switches the selected agent through the durable Session event", () =>
  400. Effect.gen(function* () {
  401. const session = yield* SessionV2.Service
  402. const created = yield* session.create({ location })
  403. yield* session.switchAgent({ sessionID: created.id, agent: "plan" })
  404. expect(yield* session.get(created.id)).toMatchObject({ agent: "plan" })
  405. expect(
  406. Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)),
  407. ).toMatchObject([{ type: "session.next.agent.switched", data: { agent: "plan" } }])
  408. }),
  409. )
  410. it.effect("rejects an agent switch for a missing Session", () =>
  411. Effect.gen(function* () {
  412. const session = yield* SessionV2.Service
  413. const missing = SessionV2.ID.make("ses_missing_agent_switch")
  414. expect(
  415. yield* session.switchAgent({ sessionID: missing, agent: "plan" }).pipe(
  416. Effect.flip,
  417. Effect.map((error) => error._tag),
  418. ),
  419. ).toBe("Session.NotFoundError")
  420. }),
  421. )
  422. it.effect("switches the selected model through the durable Session event", () =>
  423. Effect.gen(function* () {
  424. const session = yield* SessionV2.Service
  425. const created = yield* session.create({ location })
  426. const model = ModelV2.Ref.make({
  427. id: ModelV2.ID.make("sonnet"),
  428. providerID: ProviderV2.ID.anthropic,
  429. variant: ModelV2.VariantID.make("high"),
  430. })
  431. yield* session.switchModel({ sessionID: created.id, model })
  432. expect(yield* session.get(created.id)).toMatchObject({ model })
  433. expect(
  434. Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)),
  435. ).toMatchObject([{ type: "session.next.model.switched", data: { model } }])
  436. }),
  437. )
  438. it.effect("ignores a model switch when the selected model is unchanged", () =>
  439. Effect.gen(function* () {
  440. const session = yield* SessionV2.Service
  441. const created = yield* session.create({ location })
  442. const model = ModelV2.Ref.make({ id: ModelV2.ID.make("sonnet"), providerID: ProviderV2.ID.anthropic })
  443. yield* session.switchModel({ sessionID: created.id, model })
  444. yield* session.switchModel({ sessionID: created.id, model })
  445. const { db } = yield* Database.Service
  446. expect(
  447. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).all().pipe(Effect.orDie),
  448. ).toHaveLength(2)
  449. expect(yield* session.get(created.id)).toMatchObject({ model })
  450. }),
  451. )
  452. it.effect("treats an omitted variant as the default variant", () =>
  453. Effect.gen(function* () {
  454. const session = yield* SessionV2.Service
  455. const model = ModelV2.Ref.make({ id: ModelV2.ID.make("sonnet"), providerID: ProviderV2.ID.anthropic })
  456. const created = yield* session.create({ location, model })
  457. yield* session.switchModel({
  458. sessionID: created.id,
  459. model: ModelV2.Ref.make({ ...model, variant: ModelV2.VariantID.make("default") }),
  460. })
  461. const { db } = yield* Database.Service
  462. expect(
  463. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).all().pipe(Effect.orDie),
  464. ).toHaveLength(1)
  465. }),
  466. )
  467. it.effect("rejects a model switch for a missing Session", () =>
  468. Effect.gen(function* () {
  469. const session = yield* SessionV2.Service
  470. const missing = SessionV2.ID.make("ses_missing_model_switch")
  471. expect(
  472. yield* session
  473. .switchModel({
  474. sessionID: missing,
  475. model: ModelV2.Ref.make({ id: ModelV2.ID.make("sonnet"), providerID: ProviderV2.ID.anthropic }),
  476. })
  477. .pipe(
  478. Effect.flip,
  479. Effect.map((error) => error._tag),
  480. ),
  481. ).toBe("Session.NotFoundError")
  482. }),
  483. )
  484. })