httpapi-session.test.ts 9.4 KB

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