httpapi-session.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { afterEach, describe, expect } from "bun:test"
  2. import { Effect } from "effect"
  3. import { Flag } from "@opencode-ai/core/flag/flag"
  4. import { PermissionID } from "../../src/permission/schema"
  5. import { ModelID, ProviderID } from "../../src/provider/schema"
  6. import { Instance } from "../../src/project/instance"
  7. import { Server } from "../../src/server/server"
  8. import { SessionPaths } from "../../src/server/routes/instance/httpapi/session"
  9. import { Session } from "@/session/session"
  10. import { MessageID, PartID, type SessionID } from "../../src/session/schema"
  11. import { MessageV2 } from "../../src/session/message-v2"
  12. import * as Log from "@opencode-ai/core/util/log"
  13. import { resetDatabase } from "../fixture/db"
  14. import { tmpdir } from "../fixture/fixture"
  15. import { it } from "../lib/effect"
  16. void Log.init({ print: false })
  17. const original = Flag.OPENCODE_EXPERIMENTAL_HTTPAPI
  18. function app() {
  19. Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = true
  20. return Server.Default().app
  21. }
  22. function runSession<A, E>(fx: Effect.Effect<A, E, Session.Service>) {
  23. return Effect.runPromise(fx.pipe(Effect.provide(Session.defaultLayer)))
  24. }
  25. function pathFor(path: string, params: Record<string, string>) {
  26. return Object.entries(params).reduce((result, [key, value]) => result.replace(`:${key}`, value), path)
  27. }
  28. function createSession(directory: string, input?: Session.CreateInput) {
  29. return Effect.promise(
  30. async () =>
  31. await Instance.provide({
  32. directory,
  33. fn: () => runSession(Session.Service.use((svc) => svc.create(input))),
  34. }),
  35. )
  36. }
  37. function createTextMessage(directory: string, sessionID: SessionID, text: string) {
  38. return Effect.promise(
  39. async () =>
  40. await Instance.provide({
  41. directory,
  42. fn: () =>
  43. runSession(
  44. Effect.gen(function* () {
  45. const svc = yield* Session.Service
  46. const info = yield* svc.updateMessage({
  47. id: MessageID.ascending(),
  48. role: "user",
  49. sessionID,
  50. agent: "build",
  51. model: { providerID: ProviderID.make("test"), modelID: ModelID.make("test") },
  52. time: { created: Date.now() },
  53. })
  54. const part = yield* svc.updatePart({
  55. id: PartID.ascending(),
  56. sessionID,
  57. messageID: info.id,
  58. type: "text",
  59. text,
  60. })
  61. return { info, part }
  62. }),
  63. ),
  64. }),
  65. )
  66. }
  67. function request(path: string, init?: RequestInit) {
  68. return Effect.promise(async () => app().request(path, init))
  69. }
  70. function json<T>(response: Response) {
  71. return Effect.promise(async () => {
  72. if (response.status !== 200) throw new Error(await response.text())
  73. return (await response.json()) as T
  74. })
  75. }
  76. function requestJson<T>(path: string, init?: RequestInit) {
  77. return request(path, init).pipe(Effect.flatMap(json<T>))
  78. }
  79. function withTmp<A, E, R>(
  80. options: Parameters<typeof tmpdir>[0],
  81. fn: (tmp: Awaited<ReturnType<typeof tmpdir>>) => Effect.Effect<A, E, R>,
  82. ) {
  83. return Effect.acquireRelease(
  84. Effect.promise(() => tmpdir(options)),
  85. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  86. ).pipe(Effect.flatMap(fn))
  87. }
  88. afterEach(async () => {
  89. Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = original
  90. await Instance.disposeAll()
  91. await resetDatabase()
  92. })
  93. describe("session HttpApi", () => {
  94. it.live(
  95. "serves read routes through Hono bridge",
  96. withTmp({ git: true, config: { formatter: false, lsp: false } }, (tmp) =>
  97. Effect.gen(function* () {
  98. const headers = { "x-opencode-directory": tmp.path }
  99. const parent = yield* createSession(tmp.path, { title: "parent" })
  100. const child = yield* createSession(tmp.path, { title: "child", parentID: parent.id })
  101. const message = yield* createTextMessage(tmp.path, parent.id, "hello")
  102. yield* createTextMessage(tmp.path, parent.id, "world")
  103. const listed = yield* requestJson<Session.Info[]>(`${SessionPaths.list}?roots=true`, { headers })
  104. expect(listed.map((item) => item.id)).toContain(parent.id)
  105. expect(Object.hasOwn(listed[0]!, "parentID")).toBe(false)
  106. expect(yield* requestJson<Record<string, unknown>>(SessionPaths.status, { headers })).toEqual({})
  107. expect(
  108. yield* requestJson<Session.Info>(pathFor(SessionPaths.get, { sessionID: parent.id }), { headers }),
  109. ).toMatchObject({ id: parent.id, title: "parent" })
  110. expect(
  111. (yield* requestJson<Session.Info[]>(pathFor(SessionPaths.children, { sessionID: parent.id }), {
  112. headers,
  113. })).map((item) => item.id),
  114. ).toEqual([child.id])
  115. expect(
  116. yield* requestJson<unknown[]>(pathFor(SessionPaths.todo, { sessionID: parent.id }), { headers }),
  117. ).toEqual([])
  118. expect(
  119. yield* requestJson<unknown[]>(pathFor(SessionPaths.diff, { sessionID: parent.id }), { headers }),
  120. ).toEqual([])
  121. const messages = yield* request(`${pathFor(SessionPaths.messages, { sessionID: parent.id })}?limit=1`, {
  122. headers,
  123. })
  124. const messagePage = yield* json<MessageV2.WithParts[]>(messages)
  125. const nextCursor = messages.headers.get("x-next-cursor")
  126. expect(nextCursor).toBeTruthy()
  127. expect(messagePage[0]?.parts[0]).toMatchObject({ type: "text" })
  128. expect(
  129. (yield* request(`${pathFor(SessionPaths.messages, { sessionID: parent.id })}?before=${nextCursor}`, {
  130. headers,
  131. })).status,
  132. ).toBe(400)
  133. expect(
  134. (yield* request(`${pathFor(SessionPaths.messages, { sessionID: parent.id })}?limit=1&before=invalid`, {
  135. headers,
  136. })).status,
  137. ).toBe(400)
  138. expect(
  139. yield* requestJson<MessageV2.WithParts>(
  140. pathFor(SessionPaths.message, { sessionID: parent.id, messageID: message.info.id }),
  141. { headers },
  142. ),
  143. ).toMatchObject({ info: { id: message.info.id } })
  144. }),
  145. ),
  146. )
  147. it.live(
  148. "serves lifecycle mutation routes through Hono bridge",
  149. withTmp({ git: true, config: { formatter: false, lsp: false, share: "disabled" } }, (tmp) =>
  150. Effect.gen(function* () {
  151. const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }
  152. const createdEmpty = yield* requestJson<Session.Info>(SessionPaths.create, {
  153. method: "POST",
  154. headers,
  155. })
  156. expect(createdEmpty.id).toBeTruthy()
  157. const created = yield* requestJson<Session.Info>(SessionPaths.create, {
  158. method: "POST",
  159. headers,
  160. body: JSON.stringify({ title: "created" }),
  161. })
  162. expect(created.title).toBe("created")
  163. const updated = yield* requestJson<Session.Info>(pathFor(SessionPaths.update, { sessionID: created.id }), {
  164. method: "PATCH",
  165. headers,
  166. body: JSON.stringify({ title: "updated", time: { archived: 1 } }),
  167. })
  168. expect(updated).toMatchObject({ id: created.id, title: "updated", time: { archived: 1 } })
  169. const forked = yield* requestJson<Session.Info>(pathFor(SessionPaths.fork, { sessionID: created.id }), {
  170. method: "POST",
  171. headers,
  172. body: JSON.stringify({}),
  173. })
  174. expect(forked.id).not.toBe(created.id)
  175. expect(
  176. yield* requestJson<boolean>(pathFor(SessionPaths.abort, { sessionID: created.id }), {
  177. method: "POST",
  178. headers,
  179. }),
  180. ).toBe(true)
  181. expect(
  182. yield* requestJson<boolean>(pathFor(SessionPaths.remove, { sessionID: created.id }), {
  183. method: "DELETE",
  184. headers,
  185. }),
  186. ).toBe(true)
  187. }),
  188. ),
  189. )
  190. it.live(
  191. "serves message mutation routes through Hono bridge",
  192. withTmp({ git: true, config: { formatter: false, lsp: false } }, (tmp) =>
  193. Effect.gen(function* () {
  194. const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }
  195. const session = yield* createSession(tmp.path, { title: "messages" })
  196. const first = yield* createTextMessage(tmp.path, session.id, "first")
  197. const second = yield* createTextMessage(tmp.path, session.id, "second")
  198. const updated = yield* requestJson<MessageV2.Part>(
  199. pathFor(SessionPaths.updatePart, {
  200. sessionID: session.id,
  201. messageID: first.info.id,
  202. partID: first.part.id,
  203. }),
  204. {
  205. method: "PATCH",
  206. headers,
  207. body: JSON.stringify({ ...first.part, text: "updated" }),
  208. },
  209. )
  210. expect(updated).toMatchObject({ id: first.part.id, type: "text", text: "updated" })
  211. expect(
  212. yield* requestJson<boolean>(
  213. pathFor(SessionPaths.deletePart, {
  214. sessionID: session.id,
  215. messageID: first.info.id,
  216. partID: first.part.id,
  217. }),
  218. { method: "DELETE", headers },
  219. ),
  220. ).toBe(true)
  221. expect(
  222. yield* requestJson<boolean>(
  223. pathFor(SessionPaths.deleteMessage, { sessionID: session.id, messageID: second.info.id }),
  224. { method: "DELETE", headers },
  225. ),
  226. ).toBe(true)
  227. }),
  228. ),
  229. )
  230. it.live(
  231. "serves remaining non-LLM session mutation routes through Hono bridge",
  232. withTmp({ git: true, config: { formatter: false, lsp: false } }, (tmp) =>
  233. Effect.gen(function* () {
  234. const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }
  235. const session = yield* createSession(tmp.path, { title: "remaining" })
  236. expect(
  237. yield* requestJson<Session.Info>(pathFor(SessionPaths.revert, { sessionID: session.id }), {
  238. method: "POST",
  239. headers,
  240. body: JSON.stringify({ messageID: MessageID.ascending() }),
  241. }),
  242. ).toMatchObject({ id: session.id })
  243. expect(
  244. yield* requestJson<Session.Info>(pathFor(SessionPaths.unrevert, { sessionID: session.id }), {
  245. method: "POST",
  246. headers,
  247. }),
  248. ).toMatchObject({ id: session.id })
  249. expect(
  250. yield* requestJson<boolean>(
  251. pathFor(SessionPaths.permissions, {
  252. sessionID: session.id,
  253. permissionID: String(PermissionID.ascending()),
  254. }),
  255. {
  256. method: "POST",
  257. headers,
  258. body: JSON.stringify({ response: "once" }),
  259. },
  260. ),
  261. ).toBe(true)
  262. }),
  263. ),
  264. )
  265. })