httpapi-pty.test.ts 12 KB

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