httpapi-pty.test.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import { afterEach, describe, expect, test } from "bun:test"
  2. import { NodeHttpServer, NodeServices } from "@effect/platform-node"
  3. import { PtyID } from "../../src/pty/schema"
  4. import { Server } from "../../src/server/server"
  5. import { PtyPaths } from "../../src/server/routes/instance/httpapi/groups/pty"
  6. import * as Log from "@opencode-ai/core/util/log"
  7. import { resetDatabase } from "../fixture/db"
  8. import { disposeAllInstances, tmpdir, tmpdirScoped } from "../fixture/fixture"
  9. import { Config, Effect, Layer, Queue, Schema } from "effect"
  10. import { HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http"
  11. import * as Socket from "effect/unstable/socket/Socket"
  12. import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server"
  13. import { Pty } from "../../src/pty"
  14. import { testEffect } from "../lib/effect"
  15. void Log.init({ print: false })
  16. const testPty = process.platform === "win32" ? test.skip : test
  17. const testStateLayer = Layer.effectDiscard(
  18. Effect.gen(function* () {
  19. yield* Effect.promise(() => resetDatabase())
  20. yield* Effect.addFinalizer(() =>
  21. Effect.promise(async () => {
  22. await resetDatabase()
  23. }),
  24. )
  25. }),
  26. )
  27. const servedRoutes: Layer.Layer<never, Config.ConfigError, HttpServer.HttpServer> = HttpRouter.serve(
  28. HttpApiApp.routes,
  29. { disableListenLog: true, disableLogger: true },
  30. )
  31. const effectIt = testEffect(
  32. Layer.mergeAll(
  33. testStateLayer,
  34. Socket.layerWebSocketConstructorGlobal,
  35. servedRoutes.pipe(
  36. Layer.provide(Socket.layerWebSocketConstructorGlobal),
  37. Layer.provideMerge(NodeHttpServer.layerTest),
  38. Layer.provideMerge(NodeServices.layer),
  39. ),
  40. ),
  41. )
  42. function app() {
  43. return Server.Default().app
  44. }
  45. function serverUrl() {
  46. return HttpServer.HttpServer.use((server) => Effect.succeed(HttpServer.formatAddress(server.address)))
  47. }
  48. const directoryHeader = (dir: string) => HttpClientRequest.setHeader("x-opencode-directory", dir)
  49. afterEach(async () => {
  50. await disposeAllInstances()
  51. await resetDatabase()
  52. })
  53. describe("pty HttpApi bridge", () => {
  54. test("serves available shell list through experimental Effect routes", async () => {
  55. await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
  56. const response = await app().request(PtyPaths.shells, { headers: { "x-opencode-directory": tmp.path } })
  57. expect(response.status).toBe(200)
  58. expect(await response.json()).toEqual(
  59. expect.arrayContaining([
  60. expect.objectContaining({
  61. path: expect.any(String),
  62. name: expect.any(String),
  63. acceptable: expect.any(Boolean),
  64. }),
  65. ]),
  66. )
  67. })
  68. testPty("serves PTY JSON routes through experimental Effect routes", async () => {
  69. await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
  70. const headers = { "x-opencode-directory": tmp.path }
  71. const list = await app().request(PtyPaths.list, { headers })
  72. expect(list.status).toBe(200)
  73. expect(await list.json()).toEqual([])
  74. const created = await app().request(PtyPaths.create, {
  75. method: "POST",
  76. headers: { ...headers, "content-type": "application/json" },
  77. body: JSON.stringify({ command: "/usr/bin/env", args: ["sh", "-c", "sleep 5"], title: "demo" }),
  78. })
  79. expect(created.status).toBe(200)
  80. const info = await created.json()
  81. try {
  82. expect(info).toMatchObject({ title: "demo", command: "/usr/bin/env", status: "running" })
  83. const found = await app().request(PtyPaths.get.replace(":ptyID", info.id), { headers })
  84. expect(found.status).toBe(200)
  85. expect(await found.json()).toMatchObject({ id: info.id, title: "demo" })
  86. const updated = await app().request(PtyPaths.update.replace(":ptyID", info.id), {
  87. method: "PUT",
  88. headers: { ...headers, "content-type": "application/json" },
  89. body: JSON.stringify({ title: "renamed", size: { cols: 80, rows: 24 } }),
  90. })
  91. expect(updated.status).toBe(200)
  92. expect(await updated.json()).toMatchObject({ id: info.id, title: "renamed" })
  93. } finally {
  94. await app().request(PtyPaths.remove.replace(":ptyID", info.id), { method: "DELETE", headers })
  95. }
  96. const missing = await app().request(PtyPaths.get.replace(":ptyID", info.id), { headers })
  97. expect(missing.status).toBe(404)
  98. expect(await missing.json()).toEqual({
  99. _tag: "PtyNotFoundError",
  100. ptyID: info.id,
  101. message: `PTY session not found: ${info.id}`,
  102. })
  103. const missingUpdate = await app().request(PtyPaths.update.replace(":ptyID", info.id), {
  104. method: "PUT",
  105. headers: { ...headers, "content-type": "application/json" },
  106. body: JSON.stringify({ title: "missing" }),
  107. })
  108. expect(missingUpdate.status).toBe(404)
  109. expect(await missingUpdate.json()).toEqual({
  110. _tag: "PtyNotFoundError",
  111. ptyID: info.id,
  112. message: `PTY session not found: ${info.id}`,
  113. })
  114. const missingRemove = await app().request(PtyPaths.remove.replace(":ptyID", info.id), { method: "DELETE", headers })
  115. expect(missingRemove.status).toBe(404)
  116. expect(await missingRemove.json()).toEqual({
  117. _tag: "PtyNotFoundError",
  118. ptyID: info.id,
  119. message: `PTY session not found: ${info.id}`,
  120. })
  121. })
  122. test("returns 404 for missing PTY websocket before upgrade", async () => {
  123. await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
  124. const response = await app().request(PtyPaths.connect.replace(":ptyID", PtyID.ascending()), {
  125. headers: { "x-opencode-directory": tmp.path },
  126. })
  127. expect(response.status).toBe(404)
  128. })
  129. test("returns 404 for missing PTY websocket before decoding cursor query", async () => {
  130. await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
  131. const response = await app().request(`${PtyPaths.connect.replace(":ptyID", PtyID.ascending())}?cursor=a&cursor=b`, {
  132. headers: { "x-opencode-directory": tmp.path },
  133. })
  134. expect(response.status).toBe(404)
  135. })
  136. test("returns typed not found errors for missing PTY HTTP resources", async () => {
  137. await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
  138. const headers = { "x-opencode-directory": tmp.path }
  139. const missingID = String(PtyID.ascending())
  140. const expected = {
  141. _tag: "PtyNotFoundError",
  142. ptyID: missingID,
  143. message: `PTY session not found: ${missingID}`,
  144. }
  145. const found = await app().request(PtyPaths.get.replace(":ptyID", missingID), { headers })
  146. expect(found.status).toBe(404)
  147. expect(await found.json()).toEqual(expected)
  148. const updated = await app().request(PtyPaths.update.replace(":ptyID", missingID), {
  149. method: "PUT",
  150. headers: { ...headers, "content-type": "application/json" },
  151. body: JSON.stringify({ title: "missing" }),
  152. })
  153. expect(updated.status).toBe(404)
  154. expect(await updated.json()).toEqual(expected)
  155. const removed = await app().request(PtyPaths.remove.replace(":ptyID", missingID), { method: "DELETE", headers })
  156. expect(removed.status).toBe(404)
  157. expect(await removed.json()).toEqual(expected)
  158. })
  159. test("returns typed errors for PTY connect token failures", async () => {
  160. await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
  161. const headers = { "x-opencode-directory": tmp.path }
  162. const missingID = String(PtyID.ascending())
  163. const forbidden = await app().request(PtyPaths.connectToken.replace(":ptyID", missingID), {
  164. method: "POST",
  165. headers,
  166. })
  167. expect(forbidden.status).toBe(403)
  168. expect(await forbidden.json()).toEqual({
  169. _tag: "PtyForbiddenError",
  170. message: "Invalid PTY connect token request",
  171. })
  172. const missing = await app().request(PtyPaths.connectToken.replace(":ptyID", missingID), {
  173. method: "POST",
  174. headers: {
  175. ...headers,
  176. "x-opencode-ticket": "1",
  177. },
  178. })
  179. expect(missing.status).toBe(404)
  180. expect(await missing.json()).toEqual({
  181. _tag: "PtyNotFoundError",
  182. ptyID: missingID,
  183. message: `PTY session not found: ${missingID}`,
  184. })
  185. })
  186. ;(process.platform === "win32" ? effectIt.live.skip : effectIt.live)(
  187. "serves PTY websocket output and input through Effect routes",
  188. () =>
  189. Effect.gen(function* () {
  190. const dir = yield* tmpdirScoped({ git: true, config: { formatter: false, lsp: false } })
  191. const created = yield* HttpClientRequest.post(PtyPaths.create).pipe(
  192. directoryHeader(dir),
  193. HttpClientRequest.bodyJson({ command: "/bin/cat", title: "websocket" }),
  194. Effect.flatMap(HttpClient.execute),
  195. )
  196. expect(created.status).toBe(200)
  197. const info = yield* Schema.decodeUnknownEffect(Pty.Info)(yield* created.json)
  198. const socket = yield* Socket.makeWebSocket(
  199. `${(yield* serverUrl()).replace(/^http/, "ws")}${PtyPaths.connect.replace(":ptyID", info.id)}?cursor=-1&directory=${encodeURIComponent(dir)}`,
  200. { closeCodeIsError: () => false },
  201. )
  202. const messages = yield* Queue.unbounded<string>()
  203. yield* socket
  204. .runRaw((message) =>
  205. Queue.offer(messages, typeof message === "string" ? message : new TextDecoder().decode(message)),
  206. )
  207. .pipe(Effect.catch(() => Effect.void))
  208. .pipe(Effect.forkScoped)
  209. const write = yield* socket.writer
  210. const takeUntil = (expected: string, seen = ""): Effect.Effect<string, unknown> =>
  211. Effect.gen(function* () {
  212. const next = seen + (yield* Queue.take(messages).pipe(Effect.timeout("5 seconds")))
  213. if (next.includes(expected)) return next
  214. return yield* takeUntil(expected, next)
  215. })
  216. yield* write("ping-route\n")
  217. expect(yield* takeUntil("ping-route")).toContain("ping-route")
  218. yield* write(new Socket.CloseEvent(1000, "done")).pipe(Effect.catch(() => Effect.void))
  219. const removed = yield* HttpClientRequest.delete(PtyPaths.remove.replace(":ptyID", info.id)).pipe(
  220. directoryHeader(dir),
  221. HttpClient.execute,
  222. )
  223. expect(removed.status).toBe(200)
  224. }),
  225. )
  226. })