session-create.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. import { describe, expect } from "bun:test"
  2. import path from "path"
  3. import { DateTime, Effect, Layer, Stream } from "effect"
  4. import { Money } from "@opencode-ai/schema/money"
  5. import { Agent } from "@opencode-ai/core/agent"
  6. import { asc, eq } from "drizzle-orm"
  7. import { Database } from "@opencode-ai/core/database/database"
  8. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  9. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  10. import { Bus } from "@opencode-ai/core/bus"
  11. import { EventTable } from "@opencode-ai/core/event/sql"
  12. import { Location } from "@opencode-ai/core/location"
  13. import { Model } from "@opencode-ai/core/model"
  14. import { Project } from "@opencode-ai/core/project"
  15. import { ProjectTable } from "@opencode-ai/core/project/sql"
  16. import { Provider } from "@opencode-ai/core/provider"
  17. import { AbsolutePath, RelativePath } from "@opencode-ai/core/schema"
  18. import { Session } from "@opencode-ai/core/session"
  19. import { SessionV1 } from "@opencode-ai/core/v1/session"
  20. import { SessionMessage } from "@opencode-ai/core/session/message"
  21. import { SessionProjector } from "@opencode-ai/core/session/projector"
  22. import { SessionExecution } from "@opencode-ai/core/session/execution"
  23. import { SessionPending } from "@opencode-ai/core/session/pending"
  24. import { SessionEvent } from "@opencode-ai/core/session/event"
  25. import { SessionTable } from "@opencode-ai/core/session/sql"
  26. import { SessionStore } from "@opencode-ai/core/session/store"
  27. import { Workspace } from "@opencode-ai/core/workspace"
  28. import { testEffect } from "./lib/effect"
  29. import { tmpdir } from "./fixture/tmpdir"
  30. const projects = Layer.succeed(
  31. Project.Service,
  32. Project.Service.of({
  33. list: () => Effect.succeed([]),
  34. resolve: (directory) => Effect.succeed({ id: Project.ID.global, directory, canonical: directory }),
  35. directories: () => Effect.succeed([]),
  36. commit: () => Effect.void,
  37. }),
  38. )
  39. const it = testEffect(
  40. AppNodeBuilder.build(
  41. LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node, Session.node]),
  42. [
  43. [Project.node, projects],
  44. [SessionExecution.node, SessionExecution.noopLayer],
  45. ],
  46. ),
  47. )
  48. const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
  49. const id = Session.ID.create()
  50. /** Public session events from a `log` read, without synced markers. */
  51. const logEvents = (session: Session.Interface, sessionID: Session.ID, follow?: boolean) =>
  52. session
  53. .log({ sessionID, follow })
  54. .pipe(Stream.filter((item): item is SessionEvent.DurableEvent => !Bus.isSynced(item)))
  55. const assertCreateInputTypes = (session: Session.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: Session.ID.create(), location })
  60. }
  61. void assertCreateInputTypes
  62. function withTmp<A, E, R>(f: (directory: string) => Effect.Effect<A, E, R>) {
  63. return Effect.acquireRelease(
  64. Effect.promise(() => tmpdir()),
  65. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  66. ).pipe(Effect.flatMap((tmp) => f(tmp.path)))
  67. }
  68. describe("Session.create", () => {
  69. it.effect("creates a fresh projected session when the ID is omitted", () =>
  70. Effect.gen(function* () {
  71. const session = yield* Session.Service
  72. const first = yield* session.create({ location })
  73. const second = yield* session.create({ location })
  74. expect(second.id).not.toBe(first.id)
  75. expect((yield* session.list()).data).toHaveLength(2)
  76. }),
  77. )
  78. it.effect("returns the original session when the ID is retried", () =>
  79. Effect.gen(function* () {
  80. const session = yield* Session.Service
  81. const input = { id, location }
  82. const first = yield* session.create(input)
  83. const retried = yield* session.create(input)
  84. expect(retried).toEqual(first)
  85. expect((yield* session.list()).data).toEqual([first])
  86. }),
  87. )
  88. it.effect("stores supplied immutable create attributes", () =>
  89. Effect.gen(function* () {
  90. const session = yield* Session.Service
  91. const workspaceID = Workspace.ID.make("wrk_test")
  92. const model = Model.Ref.make({
  93. id: Model.ID.make("sonnet"),
  94. providerID: Provider.ID.anthropic,
  95. variant: Model.VariantID.make("fast"),
  96. })
  97. expect(
  98. yield* session.create({
  99. location: Location.Ref.make({ directory: location.directory, workspaceID }),
  100. agent: Agent.ID.make("build"),
  101. model,
  102. }),
  103. ).toMatchObject({ location: { directory: location.directory, workspaceID }, agent: "build", model })
  104. }),
  105. )
  106. it.effect("inherits location from an existing parent when omitted", () =>
  107. Effect.gen(function* () {
  108. const session = yield* Session.Service
  109. const parent = yield* session.create({ location })
  110. const child = yield* session.create({ parentID: parent.id, title: "child" })
  111. expect(child).toMatchObject({ parentID: parent.id, location })
  112. }),
  113. )
  114. it.effect("rejects child creation when the parent does not exist", () =>
  115. Effect.gen(function* () {
  116. const session = yield* Session.Service
  117. const missing = Session.ID.create()
  118. expect(yield* Effect.flip(session.create({ parentID: missing, title: "child" }))).toEqual(
  119. new Session.NotFoundError({ sessionID: missing }),
  120. )
  121. }),
  122. )
  123. it.effect("filters root sessions before applying the page limit", () =>
  124. Effect.gen(function* () {
  125. const session = yield* Session.Service
  126. const { db } = yield* Database.Service
  127. const staleRoot = yield* session.create({ location, title: "stale root" })
  128. const root = yield* session.create({ location, title: "root" })
  129. const children = yield* Effect.forEach(Array.from({ length: 60 }), (_, index) =>
  130. session.create({ parentID: root.id, title: `child ${index}` }),
  131. )
  132. yield* Effect.forEach(children, (item, index) =>
  133. db
  134. .update(SessionTable)
  135. .set({ time_created: index + 100, time_updated: index + 20_000 })
  136. .where(eq(SessionTable.id, item.id))
  137. .run(),
  138. )
  139. yield* db
  140. .update(SessionTable)
  141. .set({ time_created: 2, time_updated: 5_000 })
  142. .where(eq(SessionTable.id, staleRoot.id))
  143. .run()
  144. yield* db
  145. .update(SessionTable)
  146. .set({ time_created: 1, time_updated: 10_000 })
  147. .where(eq(SessionTable.id, root.id))
  148. .run()
  149. const page = yield* session.list({ directory: location.directory, parentID: null, limit: 1, order: "desc" })
  150. expect(page.data.map((item) => item.id)).toEqual([root.id])
  151. }),
  152. )
  153. it.effect("filters direct child sessions by parent ID", () =>
  154. Effect.gen(function* () {
  155. const session = yield* Session.Service
  156. const parent = yield* session.create({ location, title: "parent" })
  157. const child = yield* session.create({ parentID: parent.id, title: "child" })
  158. yield* session.create({ location, title: "other root" })
  159. const page = yield* session.list({ parentID: parent.id })
  160. expect(page.data.map((item) => item.id)).toEqual([child.id])
  161. }),
  162. )
  163. it.effect("filters project sessions by subpath", () =>
  164. Effect.gen(function* () {
  165. const session = yield* Session.Service
  166. const { db } = yield* Database.Service
  167. const root = yield* session.create({ location, title: "root" })
  168. const nested = yield* session.create({ location, title: "nested" })
  169. yield* db.update(SessionTable).set({ path: "packages/tui" }).where(eq(SessionTable.id, nested.id)).run()
  170. const page = yield* session.list({
  171. project: Project.ID.global,
  172. subpath: RelativePath.make("packages/tui"),
  173. parentID: null,
  174. })
  175. expect(page.data.map((item) => item.id)).toEqual([nested.id])
  176. expect(page.data.map((item) => item.id)).not.toContain(root.id)
  177. }),
  178. )
  179. it.effect("forks a session by replaying a durable fork event into copied projected rows", () =>
  180. Effect.gen(function* () {
  181. const session = yield* Session.Service
  182. const bus = yield* Bus.Service
  183. const { db } = yield* Database.Service
  184. const parent = yield* session.create({ location, title: "Parent" })
  185. const admitted = yield* session.prompt({
  186. sessionID: parent.id,
  187. text: "First",
  188. resume: false,
  189. })
  190. yield* SessionPending.promote(db, bus, parent.id, "steer")
  191. yield* session.synthetic({ sessionID: parent.id, text: "parent note", resume: false })
  192. yield* SessionPending.promote(db, bus, parent.id, "steer")
  193. const forked = yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } })
  194. const parentContext = yield* session.context(parent.id)
  195. const forkContext = yield* session.context(forked.id)
  196. const history = Array.from(yield* Stream.runCollect(logEvents(session, forked.id)))
  197. expect(forked).toMatchObject({ title: "Parent (fork #1)", fork: { sessionID: parent.id } })
  198. expect(forked.parentID).toBeUndefined()
  199. expect(forkContext).toMatchObject([
  200. { type: "user", text: "First" },
  201. { type: "synthetic", text: "parent note" },
  202. ])
  203. expect(forkContext.map((message) => message.id)).not.toEqual(parentContext.map((message) => message.id))
  204. expect(history).toHaveLength(1)
  205. expect(history[0]).toMatchObject({
  206. type: "session.forked",
  207. durable: { seq: 0 },
  208. data: { sessionID: forked.id, parentID: parent.id },
  209. })
  210. expect(yield* SessionPending.find(db, forkContext[0].id)).toBeUndefined()
  211. expect(yield* SessionPending.find(db, forkContext[1].id)).toBeUndefined()
  212. // Fork-copied messages have no admitted event in the fork aggregate, so
  213. // reusing their IDs as prompt IDs is conflicting reuse, not a retry.
  214. expect(
  215. yield* session
  216. .prompt({ id: forkContext[0].id, sessionID: forked.id, text: "First", resume: false })
  217. .pipe(Effect.flip),
  218. ).toMatchObject({ _tag: "Session.PromptConflictError", messageID: forkContext[0].id })
  219. yield* session.prompt({
  220. sessionID: parent.id,
  221. text: "Parent changed",
  222. resume: false,
  223. })
  224. yield* SessionPending.promote(db, bus, parent.id, "steer")
  225. yield* session.prompt({
  226. sessionID: forked.id,
  227. text: "Child continues",
  228. resume: false,
  229. })
  230. yield* SessionPending.promote(db, bus, forked.id, "steer")
  231. expect((yield* session.context(parent.id)).map((message) => message.type)).toEqual(["user", "synthetic", "user"])
  232. expect((yield* session.context(forked.id)).map((message) => message.type)).toEqual(["user", "synthetic", "user"])
  233. expect((yield* session.context(forked.id)).at(-1)).toMatchObject({ text: "Child continues" })
  234. expect(
  235. Array.from(yield* Stream.runCollect(logEvents(session, forked.id))).map(
  236. (event): number | undefined => event.durable?.seq,
  237. ),
  238. ).toEqual([0, 5, 6])
  239. expect(yield* SessionPending.find(db, admitted.id)).toBeUndefined()
  240. }),
  241. )
  242. it.effect("rejects forking an empty session", () =>
  243. Effect.gen(function* () {
  244. const session = yield* Session.Service
  245. const parent = yield* session.create({ location })
  246. expect(
  247. yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } }).pipe(Effect.flip),
  248. ).toMatchObject({ _tag: "Session.ForkEmptyError", sessionID: parent.id })
  249. }),
  250. )
  251. it.effect("forks before the selected boundary message", () =>
  252. Effect.gen(function* () {
  253. const session = yield* Session.Service
  254. const bus = yield* Bus.Service
  255. const { db } = yield* Database.Service
  256. const parent = yield* session.create({ location })
  257. const first = yield* session.prompt({
  258. sessionID: parent.id,
  259. text: "First",
  260. resume: false,
  261. })
  262. yield* SessionPending.promote(db, bus, parent.id, "steer")
  263. const second = yield* session.prompt({
  264. sessionID: parent.id,
  265. text: "Second",
  266. resume: false,
  267. })
  268. yield* SessionPending.promote(db, bus, parent.id, "steer")
  269. const assistantMessageID = SessionMessage.ID.create()
  270. const model = Model.Ref.make({ id: Model.ID.make("model"), providerID: Provider.ID.make("provider") })
  271. yield* bus.publish(SessionEvent.Step.Started, {
  272. sessionID: parent.id,
  273. assistantMessageID,
  274. agent: Agent.ID.make("build"),
  275. model,
  276. })
  277. yield* bus.publish(SessionEvent.Step.Ended, {
  278. sessionID: parent.id,
  279. assistantMessageID,
  280. finish: "stop",
  281. cost: Money.USD.make(0.75),
  282. tokens: { input: 6, output: 3, reasoning: 1, cache: { read: 2, write: 1 } },
  283. })
  284. const forked = yield* session.fork({
  285. sessionID: parent.id,
  286. boundary: { type: "before", messageID: second.id },
  287. })
  288. const beforeFirst = yield* session.fork({
  289. sessionID: parent.id,
  290. boundary: { type: "before", messageID: first.id },
  291. })
  292. const complete = yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } })
  293. const context = yield* session.context(forked.id)
  294. const history = Array.from(yield* Stream.runCollect(logEvents(session, forked.id)))
  295. expect(forked.fork).toEqual({
  296. sessionID: parent.id,
  297. boundary: { type: "before", messageID: second.id },
  298. })
  299. expect(context).toMatchObject([{ text: "First" }])
  300. expect(context[0]?.id).not.toBe(first.id)
  301. expect(history[0]).toMatchObject({
  302. data: { boundary: { type: "before", messageID: second.id } },
  303. })
  304. expect(forked).toMatchObject({ cost: 0, tokens: { input: 0, output: 0, reasoning: 0 } })
  305. expect(yield* session.context(beforeFirst.id)).toEqual([])
  306. expect(beforeFirst).toMatchObject({ cost: 0, tokens: { input: 0, output: 0, reasoning: 0 } })
  307. expect(complete).toMatchObject({
  308. cost: 0,
  309. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  310. })
  311. }),
  312. )
  313. it.effect("returns the existing Session when one ID is reused with different create arguments", () =>
  314. Effect.gen(function* () {
  315. const session = yield* Session.Service
  316. const created = yield* session.create({ id, location })
  317. const changed = [
  318. { id, location: Location.Ref.make({ directory: AbsolutePath.make("/other") }) },
  319. { id, location, agent: Agent.ID.make("build") },
  320. {
  321. id,
  322. location,
  323. model: Model.Ref.make({ id: Model.ID.make("sonnet"), providerID: Provider.ID.anthropic }),
  324. },
  325. ]
  326. for (const input of changed) {
  327. expect(yield* session.create(input)).toEqual(created)
  328. }
  329. expect((yield* session.list()).data).toHaveLength(1)
  330. }),
  331. )
  332. it.effect("returns one recorded session to concurrent exact retries", () =>
  333. Effect.gen(function* () {
  334. const session = yield* Session.Service
  335. const input = { id, location }
  336. const created = yield* Effect.all([session.create(input), session.create(input)], { concurrency: "unbounded" })
  337. expect(created[1]).toEqual(created[0])
  338. expect((yield* session.list()).data).toEqual([created[0]])
  339. }),
  340. )
  341. it.effect("returns the current Session projection after updates", () =>
  342. Effect.gen(function* () {
  343. const session = yield* Session.Service
  344. const { db } = yield* Database.Service
  345. const input = { id, location }
  346. const created = yield* session.create(input)
  347. yield* db.update(SessionTable).set({ agent: "build" }).where(eq(SessionTable.id, id)).run().pipe(Effect.orDie)
  348. expect(yield* session.create(input)).toMatchObject({ id: created.id, agent: "build" })
  349. }),
  350. )
  351. it.effect("returns the current Session projection after projected updates", () =>
  352. Effect.gen(function* () {
  353. const session = yield* Session.Service
  354. const bus = yield* Bus.Service
  355. const input = { id, location }
  356. const created = yield* session.create(input)
  357. yield* bus.publish(SessionV1.Event.Updated, {
  358. sessionID: id,
  359. info: SessionV1.SessionInfo.make({
  360. id,
  361. slug: "updated",
  362. version: "test",
  363. projectID: created.projectID,
  364. directory: created.location.directory,
  365. title: "updated",
  366. agent: "build",
  367. time: { created: 0, updated: 1 },
  368. }),
  369. })
  370. expect(yield* session.create(input)).toMatchObject({ id, agent: "build" })
  371. }),
  372. )
  373. it.effect("persists creation through the existing legacy created event", () =>
  374. Effect.gen(function* () {
  375. const session = yield* Session.Service
  376. const { db } = yield* Database.Service
  377. const created = yield* session.create({ location })
  378. expect(
  379. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).all().pipe(Effect.orDie),
  380. ).toMatchObject([{ type: Bus.versionedType(SessionV1.Event.Created.type, 1) }])
  381. }),
  382. )
  383. it.effect("persists caller-ID creation through the existing created event", () =>
  384. Effect.gen(function* () {
  385. const session = yield* Session.Service
  386. const { db } = yield* Database.Service
  387. const created = yield* session.create({ id, location })
  388. expect(
  389. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).get().pipe(Effect.orDie),
  390. ).toMatchObject({
  391. data: { sessionID: id },
  392. })
  393. }),
  394. )
  395. it.effect("omits legacy creation rows from the Session event stream", () =>
  396. Effect.gen(function* () {
  397. const session = yield* Session.Service
  398. const bus = yield* Bus.Service
  399. const { db } = yield* Database.Service
  400. const created = yield* session.create({ location })
  401. yield* session.prompt({
  402. sessionID: created.id,
  403. text: "Hello",
  404. resume: false,
  405. })
  406. yield* SessionPending.promote(db, bus, created.id, "steer")
  407. expect(
  408. Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(2), Stream.runCollect)),
  409. ).toMatchObject([
  410. {
  411. durable: { seq: 1 },
  412. type: "session.input.admitted",
  413. data: { input: { type: "user", data: { text: "Hello" }, delivery: "steer" } },
  414. },
  415. { durable: { seq: 2 }, type: "session.input.promoted" },
  416. ])
  417. }),
  418. )
  419. it.effect("replays one prompt lifecycle into a fresh target database", () =>
  420. Effect.gen(function* () {
  421. const session = yield* Session.Service
  422. const sourceEvents = yield* Bus.Service
  423. const sourceDb = (yield* Database.Service).db
  424. const created = yield* session.create({ id: Session.ID.make("ses_fresh_target_replay"), location })
  425. const admitted = yield* session.prompt({
  426. sessionID: created.id,
  427. text: "Replay lifecycle",
  428. resume: false,
  429. })
  430. yield* SessionPending.promote(sourceDb, sourceEvents, created.id, "steer")
  431. const serialized = (yield* sourceDb
  432. .select()
  433. .from(EventTable)
  434. .where(eq(EventTable.aggregate_id, created.id))
  435. .orderBy(asc(EventTable.seq))
  436. .all()
  437. .pipe(Effect.orDie)).map((event) => ({
  438. id: event.id,
  439. created: DateTime.makeUnsafe(event.created),
  440. aggregateID: event.aggregate_id,
  441. seq: event.seq,
  442. type: event.type,
  443. data: event.data,
  444. }))
  445. const tmp = yield* Effect.acquireRelease(
  446. Effect.promise(() => tmpdir()),
  447. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  448. )
  449. const targetDatabase = Database.layer({ path: path.join(tmp.path, "target.sqlite") })
  450. const targetLayer = AppNodeBuilder.build(
  451. LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node]),
  452. [[Database.node, targetDatabase]],
  453. )
  454. yield* Effect.gen(function* () {
  455. const db = (yield* Database.Service).db
  456. const bus = yield* Bus.Service
  457. const store = yield* SessionStore.Service
  458. yield* db
  459. .insert(ProjectTable)
  460. .values({ id: Project.ID.global, worktree: location.directory, sandboxes: [] })
  461. .run()
  462. .pipe(Effect.orDie)
  463. expect(yield* store.get(created.id)).toBeUndefined()
  464. expect(yield* bus.replayAll(serialized.slice(0, 2))).toBe(created.id)
  465. expect(yield* SessionPending.find(db, admitted.id)).toMatchObject({
  466. id: admitted.id,
  467. sessionID: created.id,
  468. type: "user",
  469. data: { text: "Replay lifecycle" },
  470. delivery: "steer",
  471. })
  472. expect(yield* store.context(created.id)).toEqual([])
  473. expect(yield* bus.replayAll(serialized.slice(2))).toBe(created.id)
  474. expect(yield* SessionPending.find(db, admitted.id)).toBeUndefined()
  475. expect(yield* store.context(created.id)).toMatchObject([
  476. { id: admitted.id, type: "user", text: "Replay lifecycle" },
  477. ])
  478. expect(
  479. (yield* db
  480. .select()
  481. .from(EventTable)
  482. .where(eq(EventTable.aggregate_id, created.id))
  483. .orderBy(asc(EventTable.seq))
  484. .all()
  485. .pipe(Effect.orDie)).map((event) => [event.seq, event.type]),
  486. ).toEqual([
  487. [0, Bus.versionedType(SessionV1.Event.Created.type, 1)],
  488. [1, Bus.versionedType(SessionEvent.InputAdmitted.type, 1)],
  489. [2, Bus.versionedType(SessionEvent.InputPromoted.type, 1)],
  490. ])
  491. }).pipe(Effect.provide(Layer.fresh(targetLayer)))
  492. }),
  493. )
  494. it.effect("does not mask unrelated created projector defects", () =>
  495. Effect.gen(function* () {
  496. const session = yield* Session.Service
  497. const event = yield* Bus.Service
  498. const defect = new Error("unrelated projector defect")
  499. yield* event.project(SessionV1.Event.Created, () => Effect.die(defect))
  500. expect(yield* session.create({ id, location }).pipe(Effect.catchDefect(Effect.succeed))).toBe(defect)
  501. }),
  502. )
  503. it.live("runs a shell command and projects the started/ended shell message", () =>
  504. withTmp((directory) =>
  505. Effect.gen(function* () {
  506. const session = yield* Session.Service
  507. const created = yield* session.create({
  508. location: Location.Ref.make({ directory: AbsolutePath.make(directory) }),
  509. })
  510. yield* session.shell({ sessionID: created.id, command: "echo hello" })
  511. const messages = yield* session.messages({ sessionID: created.id, order: "asc" })
  512. const shell = messages.find((message): message is SessionMessage.Shell => message.type === "shell")
  513. expect(shell).toMatchObject({ type: "shell", command: "echo hello", status: "exited", exit: 0 })
  514. expect(shell?.output?.output).toContain("hello")
  515. expect(shell?.output?.truncated).toBe(false)
  516. expect(shell?.time.completed).toBeDefined()
  517. }),
  518. ),
  519. )
  520. it.live("still emits shell ended for a failing command", () =>
  521. withTmp((directory) =>
  522. Effect.gen(function* () {
  523. const session = yield* Session.Service
  524. const created = yield* session.create({
  525. location: Location.Ref.make({ directory: AbsolutePath.make(directory) }),
  526. })
  527. yield* session.shell({ sessionID: created.id, command: "false" })
  528. const messages = yield* session.messages({ sessionID: created.id, order: "asc" })
  529. const shell = messages.find((message): message is SessionMessage.Shell => message.type === "shell")
  530. expect(shell).toMatchObject({ type: "shell", command: "false", status: "exited" })
  531. expect(shell?.exit).not.toBe(0)
  532. expect(shell?.time.completed).toBeDefined()
  533. }),
  534. ),
  535. )
  536. it.effect("switches the selected agent through the durable Session event", () =>
  537. Effect.gen(function* () {
  538. const session = yield* Session.Service
  539. const created = yield* session.create({ location })
  540. yield* session.switchAgent({ sessionID: created.id, agent: Agent.ID.make("plan") })
  541. expect(yield* session.get(created.id)).toMatchObject({ agent: "plan" })
  542. expect(
  543. Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect)),
  544. ).toMatchObject([{ type: "session.agent.selected", data: { agent: "plan" } }])
  545. }),
  546. )
  547. it.effect("rejects an agent switch for a missing Session", () =>
  548. Effect.gen(function* () {
  549. const session = yield* Session.Service
  550. const missing = Session.ID.make("ses_missing_agent_switch")
  551. expect(
  552. yield* session.switchAgent({ sessionID: missing, agent: Agent.ID.make("plan") }).pipe(
  553. Effect.flip,
  554. Effect.map((error) => error._tag),
  555. ),
  556. ).toBe("Session.NotFoundError")
  557. }),
  558. )
  559. it.effect("switches the selected model through the durable Session event", () =>
  560. Effect.gen(function* () {
  561. const session = yield* Session.Service
  562. const created = yield* session.create({ location })
  563. const model = Model.Ref.make({
  564. id: Model.ID.make("sonnet"),
  565. providerID: Provider.ID.anthropic,
  566. variant: Model.VariantID.make("high"),
  567. })
  568. yield* session.switchModel({ sessionID: created.id, model })
  569. expect(yield* session.get(created.id)).toMatchObject({ model })
  570. const bus = Array.from(yield* logEvents(session, created.id, true).pipe(Stream.take(1), Stream.runCollect))
  571. expect(bus).toMatchObject([{ type: "session.model.selected" }])
  572. expect(bus[0]?.data).toEqual({ sessionID: created.id, model })
  573. }),
  574. )
  575. it.effect("ignores a model switch when the selected model is unchanged", () =>
  576. Effect.gen(function* () {
  577. const session = yield* Session.Service
  578. const created = yield* session.create({ location })
  579. const model = Model.Ref.make({ id: Model.ID.make("sonnet"), providerID: Provider.ID.anthropic })
  580. yield* session.switchModel({ sessionID: created.id, model })
  581. yield* session.switchModel({ sessionID: created.id, model })
  582. const { db } = yield* Database.Service
  583. expect(
  584. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).all().pipe(Effect.orDie),
  585. ).toHaveLength(2)
  586. expect(yield* session.get(created.id)).toMatchObject({ model })
  587. }),
  588. )
  589. it.effect("treats an omitted variant as the default variant", () =>
  590. Effect.gen(function* () {
  591. const session = yield* Session.Service
  592. const model = Model.Ref.make({ id: Model.ID.make("sonnet"), providerID: Provider.ID.anthropic })
  593. const created = yield* session.create({ location, model })
  594. yield* session.switchModel({
  595. sessionID: created.id,
  596. model: Model.Ref.make({ ...model, variant: Model.VariantID.make("default") }),
  597. })
  598. const { db } = yield* Database.Service
  599. expect(
  600. yield* db.select().from(EventTable).where(eq(EventTable.aggregate_id, created.id)).all().pipe(Effect.orDie),
  601. ).toHaveLength(1)
  602. }),
  603. )
  604. it.effect("rejects a model switch for a missing Session", () =>
  605. Effect.gen(function* () {
  606. const session = yield* Session.Service
  607. const missing = Session.ID.make("ses_missing_model_switch")
  608. expect(
  609. yield* session
  610. .switchModel({
  611. sessionID: missing,
  612. model: Model.Ref.make({ id: Model.ID.make("sonnet"), providerID: Provider.ID.anthropic }),
  613. })
  614. .pipe(
  615. Effect.flip,
  616. Effect.map((error) => error._tag),
  617. ),
  618. ).toBe("Session.NotFoundError")
  619. }),
  620. )
  621. })