httpapi-workspace.test.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"
  2. import { mkdir } from "node:fs/promises"
  3. import path from "node:path"
  4. import { Effect } from "effect"
  5. import { Flag } from "@opencode-ai/core/flag/flag"
  6. import { registerAdaptor } from "../../src/control-plane/adaptors"
  7. import type { WorkspaceAdaptor } from "../../src/control-plane/types"
  8. import { Workspace } from "../../src/control-plane/workspace"
  9. import { WorkspacePaths } from "../../src/server/routes/instance/httpapi/groups/workspace"
  10. import { Session } from "@/session/session"
  11. import * as Log from "@opencode-ai/core/util/log"
  12. import { Server } from "../../src/server/server"
  13. import { resetDatabase } from "../fixture/db"
  14. import { tmpdir } from "../fixture/fixture"
  15. import { Instance } from "../../src/project/instance"
  16. import { InstancePaths } from "../../src/server/routes/instance/httpapi/groups/instance"
  17. void Log.init({ print: false })
  18. const originalWorkspaces = Flag.OPENCODE_EXPERIMENTAL_WORKSPACES
  19. const originalHttpApi = Flag.OPENCODE_EXPERIMENTAL_HTTPAPI
  20. function request(path: string, directory: string, init: RequestInit = {}) {
  21. Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = true
  22. const headers = new Headers(init.headers)
  23. headers.set("x-opencode-directory", directory)
  24. return Server.Default().app.request(path, { ...init, headers })
  25. }
  26. function runSession<A, E>(fx: Effect.Effect<A, E, Session.Service>) {
  27. return Effect.runPromise(fx.pipe(Effect.provide(Session.defaultLayer)))
  28. }
  29. function localAdaptor(directory: string): WorkspaceAdaptor {
  30. return {
  31. name: "Local Test",
  32. description: "Create a local test workspace",
  33. configure(info) {
  34. return {
  35. ...info,
  36. name: "local-test",
  37. directory,
  38. }
  39. },
  40. async create() {
  41. await mkdir(directory, { recursive: true })
  42. },
  43. async remove() {},
  44. target() {
  45. return {
  46. type: "local" as const,
  47. directory,
  48. }
  49. },
  50. }
  51. }
  52. function remoteAdaptor(directory: string, url: string): WorkspaceAdaptor {
  53. return {
  54. name: "Remote Test",
  55. description: "Create a remote test workspace",
  56. configure(info) {
  57. return {
  58. ...info,
  59. name: "remote-test",
  60. directory,
  61. }
  62. },
  63. async create() {
  64. await mkdir(directory, { recursive: true })
  65. },
  66. async remove() {},
  67. target() {
  68. return {
  69. type: "remote" as const,
  70. url,
  71. }
  72. },
  73. }
  74. }
  75. function eventStreamResponse() {
  76. return new Response(new ReadableStream({ start() {} }), {
  77. status: 200,
  78. headers: {
  79. "content-type": "text/event-stream",
  80. },
  81. })
  82. }
  83. afterEach(async () => {
  84. mock.restore()
  85. Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = originalWorkspaces
  86. Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = originalHttpApi
  87. await Instance.disposeAll()
  88. await resetDatabase()
  89. })
  90. describe("workspace HttpApi", () => {
  91. test("serves read endpoints", async () => {
  92. await using tmp = await tmpdir({ git: true })
  93. const [adaptors, workspaces, status] = await Promise.all([
  94. request(WorkspacePaths.adaptors, tmp.path),
  95. request(WorkspacePaths.list, tmp.path),
  96. request(WorkspacePaths.status, tmp.path),
  97. ])
  98. expect(adaptors.status).toBe(200)
  99. expect(await adaptors.json()).toEqual([
  100. {
  101. type: "worktree",
  102. name: "Worktree",
  103. description: "Create a git worktree",
  104. },
  105. ])
  106. expect(workspaces.status).toBe(200)
  107. expect(await workspaces.json()).toEqual([])
  108. expect(status.status).toBe(200)
  109. expect(await status.json()).toEqual([])
  110. })
  111. test("serves mutation endpoints", async () => {
  112. Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true
  113. await using tmp = await tmpdir({ git: true })
  114. await Instance.provide({
  115. directory: tmp.path,
  116. fn: async () =>
  117. registerAdaptor(Instance.project.id, "local-test", localAdaptor(path.join(tmp.path, ".workspace"))),
  118. })
  119. const created = await request(WorkspacePaths.list, tmp.path, {
  120. method: "POST",
  121. headers: { "content-type": "application/json" },
  122. body: JSON.stringify({ type: "local-test", branch: null, extra: null }),
  123. })
  124. expect(created.status).toBe(200)
  125. const workspace = (await created.json()) as Workspace.Info
  126. expect(workspace).toMatchObject({ type: "local-test", name: "local-test" })
  127. const session = await Instance.provide({
  128. directory: tmp.path,
  129. fn: async () => runSession(Session.Service.use((svc) => svc.create({}))),
  130. })
  131. const restored = await request(WorkspacePaths.sessionRestore.replace(":id", workspace.id), tmp.path, {
  132. method: "POST",
  133. headers: { "content-type": "application/json" },
  134. body: JSON.stringify({ sessionID: session.id }),
  135. })
  136. expect(restored.status).toBe(200)
  137. expect((await restored.json()) as { total: number }).toMatchObject({ total: expect.any(Number) })
  138. const removed = await request(WorkspacePaths.remove.replace(":id", workspace.id), tmp.path, { method: "DELETE" })
  139. expect(removed.status).toBe(200)
  140. expect(await removed.json()).toMatchObject({ id: workspace.id })
  141. const listed = await request(WorkspacePaths.list, tmp.path)
  142. expect(listed.status).toBe(200)
  143. expect(await listed.json()).toEqual([])
  144. })
  145. test("routes local workspace requests through the workspace target directory", async () => {
  146. Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true
  147. await using tmp = await tmpdir({ git: true })
  148. const workspaceDir = path.join(tmp.path, ".workspace-local")
  149. const workspace = await Instance.provide({
  150. directory: tmp.path,
  151. fn: async () => {
  152. registerAdaptor(Instance.project.id, "local-target", localAdaptor(workspaceDir))
  153. return Workspace.create({
  154. type: "local-target",
  155. branch: null,
  156. extra: null,
  157. projectID: Instance.project.id,
  158. })
  159. },
  160. })
  161. const url = new URL(`http://localhost${InstancePaths.path}`)
  162. url.searchParams.set("workspace", workspace.id)
  163. try {
  164. const response = await request(url.toString(), tmp.path)
  165. expect(response.status).toBe(200)
  166. expect(await response.json()).toMatchObject({ directory: workspaceDir })
  167. } finally {
  168. await Workspace.remove(workspace.id)
  169. }
  170. })
  171. test("proxies remote workspace HTTP requests", async () => {
  172. Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true
  173. await using tmp = await tmpdir({ git: true })
  174. const proxied: string[] = []
  175. const rawFetch = globalThis.fetch
  176. spyOn(globalThis, "fetch").mockImplementation(
  177. Object.assign(
  178. async (input: URL | RequestInfo, init?: BunFetchRequestInit | RequestInit) => {
  179. const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url)
  180. if (url.pathname === "/base/global/event") return eventStreamResponse()
  181. if (url.pathname === "/base/sync/history") return Response.json([])
  182. proxied.push(url.toString())
  183. return Response.json({ proxied: true, path: url.pathname, workspace: url.searchParams.get("workspace") })
  184. },
  185. {
  186. preconnect: rawFetch.preconnect?.bind(rawFetch),
  187. },
  188. ) as typeof globalThis.fetch,
  189. )
  190. const workspace = await Instance.provide({
  191. directory: tmp.path,
  192. fn: async () => {
  193. registerAdaptor(
  194. Instance.project.id,
  195. "remote-target",
  196. remoteAdaptor(path.join(tmp.path, ".remote"), "https://remote.test/base"),
  197. )
  198. return Workspace.create({
  199. type: "remote-target",
  200. branch: null,
  201. extra: null,
  202. projectID: Instance.project.id,
  203. })
  204. },
  205. })
  206. const url = new URL(`http://localhost${InstancePaths.path}`)
  207. url.searchParams.set("workspace", workspace.id)
  208. try {
  209. const response = await request(url.toString(), tmp.path)
  210. expect(response.status).toBe(200)
  211. expect(await response.json()).toEqual({ proxied: true, path: "/base/path", workspace: null })
  212. expect(proxied).toEqual(["https://remote.test/base/path"])
  213. } finally {
  214. await Workspace.remove(workspace.id)
  215. }
  216. })
  217. })