httpapi-instance.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import { NodeHttpServer, NodeServices } from "@effect/platform-node"
  2. import { Flag } from "@opencode-ai/core/flag/flag"
  3. import { describe, expect } from "bun:test"
  4. import { Config, Context, Effect, FileSystem, Layer, Path } from "effect"
  5. import { HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http"
  6. import * as Socket from "effect/unstable/socket/Socket"
  7. import { WorkspaceID } from "../../src/control-plane/schema"
  8. import { ControlPaths } from "../../src/server/routes/instance/httpapi/groups/control"
  9. import { InstancePaths } from "../../src/server/routes/instance/httpapi/groups/instance"
  10. import { SessionPaths } from "../../src/server/routes/instance/httpapi/groups/session"
  11. import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server"
  12. import { HEADER as FenceHeader } from "../../src/server/shared/fence"
  13. import { resetDatabase } from "../fixture/db"
  14. import { tmpdirScoped } from "../fixture/fixture"
  15. import { testEffect } from "../lib/effect"
  16. // Flip the experimental workspaces flag so SyncEvent.run actually writes to
  17. // EventSequenceTable (the source of truth the fence middleware reads). Reset
  18. // the database around the test so per-instance state does not leak between
  19. // runs. resetDatabase() already calls disposeAllInstances(), so we don't
  20. // repeat it.
  21. const testStateLayer = Layer.effectDiscard(
  22. Effect.gen(function* () {
  23. const originalWorkspaces = Flag.OPENCODE_EXPERIMENTAL_WORKSPACES
  24. Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true
  25. yield* Effect.promise(() => resetDatabase())
  26. yield* Effect.addFinalizer(() =>
  27. Effect.promise(async () => {
  28. Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = originalWorkspaces
  29. await resetDatabase()
  30. }),
  31. )
  32. }),
  33. )
  34. // Mount the production HttpApi route tree on a real Node HTTP server bound to
  35. // 127.0.0.1:0 and a fetch-based HttpClient that prepends the server URL. This
  36. // keeps the test wired directly through the same route layer production uses.
  37. const servedRoutes: Layer.Layer<never, Config.ConfigError, HttpServer.HttpServer> = HttpRouter.serve(
  38. HttpApiApp.routes,
  39. { disableListenLog: true, disableLogger: true },
  40. )
  41. const httpApiServerLayer = servedRoutes.pipe(
  42. Layer.provide(Socket.layerWebSocketConstructorGlobal),
  43. Layer.provideMerge(NodeHttpServer.layerTest),
  44. Layer.provideMerge(NodeServices.layer),
  45. )
  46. const it = testEffect(Layer.mergeAll(testStateLayer, httpApiServerLayer))
  47. const handlerContext = Context.empty() as Context.Context<unknown>
  48. const directoryHeader = (dir: string) => HttpClientRequest.setHeader("x-opencode-directory", dir)
  49. describe("instance HttpApi", () => {
  50. it.live("serves the OpenAPI document", () =>
  51. Effect.gen(function* () {
  52. const response = yield* HttpClient.get("/doc")
  53. expect(response.status).toBe(200)
  54. expect(response.headers["content-type"]).toContain("application/json")
  55. expect(yield* response.json).toMatchObject({
  56. openapi: expect.any(String),
  57. info: expect.any(Object),
  58. paths: expect.objectContaining({
  59. "/global/health": expect.any(Object),
  60. "/session": expect.any(Object),
  61. }),
  62. })
  63. }),
  64. )
  65. it.live("emits a sync fence header for fixed-workspace mutations", () =>
  66. Effect.gen(function* () {
  67. const originalWorkspaceID = Flag.OPENCODE_WORKSPACE_ID
  68. Flag.OPENCODE_WORKSPACE_ID = WorkspaceID.ascending()
  69. yield* Effect.addFinalizer(() =>
  70. Effect.sync(() => {
  71. Flag.OPENCODE_WORKSPACE_ID = originalWorkspaceID
  72. }),
  73. )
  74. const dir = yield* tmpdirScoped({ git: true })
  75. const response = yield* HttpClientRequest.post(SessionPaths.create).pipe(
  76. directoryHeader(dir),
  77. HttpClientRequest.bodyJson({ title: "fenced" }),
  78. Effect.flatMap(HttpClient.execute),
  79. )
  80. expect(response.status).toBe(200)
  81. expect(JSON.parse(response.headers[FenceHeader] ?? "{}")).not.toEqual({})
  82. }),
  83. )
  84. it.live("does not emit sync fence headers for fixed-workspace reads or no-op mutations", () =>
  85. Effect.gen(function* () {
  86. const originalWorkspaceID = Flag.OPENCODE_WORKSPACE_ID
  87. Flag.OPENCODE_WORKSPACE_ID = WorkspaceID.ascending()
  88. yield* Effect.addFinalizer(() =>
  89. Effect.sync(() => {
  90. Flag.OPENCODE_WORKSPACE_ID = originalWorkspaceID
  91. }),
  92. )
  93. const dir = yield* tmpdirScoped({ git: true })
  94. const read = yield* HttpClientRequest.get(InstancePaths.path).pipe(directoryHeader(dir), HttpClient.execute)
  95. const log = yield* HttpClientRequest.post(ControlPaths.log).pipe(
  96. directoryHeader(dir),
  97. HttpClientRequest.bodyJson({ service: "fence-test", level: "info", message: "noop" }),
  98. Effect.flatMap(HttpClient.execute),
  99. )
  100. expect(read.status).toBe(200)
  101. expect(read.headers[FenceHeader]).toBeUndefined()
  102. expect(log.status).toBe(200)
  103. expect(log.headers[FenceHeader]).toBeUndefined()
  104. }),
  105. )
  106. it.live("rejects malformed permission and question request ids", () =>
  107. Effect.gen(function* () {
  108. const dir = yield* tmpdirScoped({ git: true })
  109. const request = (path: string, init?: RequestInit) =>
  110. Effect.promise(() =>
  111. HttpApiApp.webHandler().handler(
  112. new Request(`http://localhost${path}`, {
  113. ...init,
  114. headers: { "x-opencode-directory": dir, "content-type": "application/json", ...init?.headers },
  115. }),
  116. handlerContext,
  117. ),
  118. )
  119. const [permission, questionReply, questionReject] = yield* Effect.all(
  120. [
  121. request("/permission/invalid-permission-id/reply", {
  122. method: "POST",
  123. body: JSON.stringify({ reply: "once" }),
  124. }),
  125. request("/question/invalid-question-id/reply", {
  126. method: "POST",
  127. body: JSON.stringify({ answers: [["Yes"]] }),
  128. }),
  129. request("/question/invalid-question-id/reject", { method: "POST" }),
  130. ],
  131. { concurrency: "unbounded" },
  132. )
  133. expect(permission.status).toBe(400)
  134. expect(questionReply.status).toBe(400)
  135. expect(questionReject.status).toBe(400)
  136. }),
  137. )
  138. it.live("serves path and VCS read endpoints", () =>
  139. Effect.gen(function* () {
  140. const dir = yield* tmpdirScoped({ git: true })
  141. const fs = yield* FileSystem.FileSystem
  142. const path = yield* Path.Path
  143. yield* fs.writeFileString(path.join(dir, "changed.txt"), "hello")
  144. const [paths, vcs, diff] = yield* Effect.all(
  145. [
  146. HttpClientRequest.get(InstancePaths.path).pipe(directoryHeader(dir), HttpClient.execute),
  147. HttpClientRequest.get(InstancePaths.vcs).pipe(directoryHeader(dir), HttpClient.execute),
  148. HttpClientRequest.get(InstancePaths.vcsDiff).pipe(
  149. HttpClientRequest.setUrlParam("mode", "git"),
  150. directoryHeader(dir),
  151. HttpClient.execute,
  152. ),
  153. ],
  154. { concurrency: "unbounded" },
  155. )
  156. expect(paths.status).toBe(200)
  157. expect(yield* paths.json).toMatchObject({ directory: dir, worktree: dir })
  158. expect(vcs.status).toBe(200)
  159. expect(yield* vcs.json).toMatchObject({ branch: expect.any(String) })
  160. expect(diff.status).toBe(200)
  161. expect(yield* diff.json).toContainEqual(
  162. expect.objectContaining({ file: "changed.txt", additions: 1, status: "added" }),
  163. )
  164. }),
  165. )
  166. })