mock-server.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import type { Page, Route } from "@playwright/test"
  2. const emptyList = new Set(["/skill", "/command", "/lsp", "/formatter", "/vcs/status", "/vcs/diff"])
  3. const emptyObject = new Set(["/global/config", "/config", "/provider/auth", "/mcp", "/experimental/resource"])
  4. export interface MockServerConfig {
  5. provider: unknown
  6. directory: string
  7. project: unknown
  8. sessions: ({ id: string } & Record<string, unknown>)[]
  9. pageMessages: (sessionId: string, limit: number, before?: string) => { items: unknown[]; cursor?: string }
  10. vcsDiff?: unknown[]
  11. messageDelay?: number
  12. beforeMessagesResponse?: (input: { sessionID: string; before?: string }) => Promise<void>
  13. onMessages?: (input: { sessionID: string; before?: string; phase: "start" | "end" }) => void
  14. message?: (sessionID: string, messageID: string) => unknown
  15. onMessage?: (input: { sessionID: string; messageID: string }) => void
  16. events?: () => unknown[]
  17. eventRetry?: number
  18. permissions?: unknown[] | (() => unknown[])
  19. questions?: unknown[] | (() => unknown[])
  20. fileList?: (path: string) => unknown | Promise<unknown>
  21. fileContent?: (path: string) => unknown | Promise<unknown>
  22. findFiles?: (input: { query: string; dirs?: string; limit?: number }) => unknown
  23. sessionStatus?: unknown
  24. }
  25. export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
  26. const cursors = new Map<string, string>()
  27. let nextCursor = 0
  28. const staticRoutes: Record<string, unknown> = {
  29. "/provider": config.provider,
  30. "/path": {
  31. state: config.directory,
  32. config: config.directory,
  33. worktree: config.directory,
  34. directory: config.directory,
  35. home: "C:/OpenCode",
  36. },
  37. "/project": [config.project],
  38. "/project/current": config.project,
  39. "/agent": [{ name: "build", mode: "primary" }],
  40. "/vcs": { branch: "main", default_branch: "main" },
  41. "/session": config.sessions,
  42. }
  43. await page.route("**/*", async (route) => {
  44. const url = new URL(route.request().url())
  45. const targetPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
  46. const appPort = new URL(
  47. process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${process.env.PLAYWRIGHT_PORT ?? "3000"}`,
  48. ).port
  49. if (url.port !== targetPort && url.port !== appPort) return route.fallback()
  50. const path = url.pathname
  51. if (path === "/global/event" || path === "/event") return sse(route, config.events?.(), config.eventRetry)
  52. if (path === "/global/health") return json(route, { healthy: true })
  53. if (path === "/experimental/capabilities") return json(route, { backgroundSubagents: true })
  54. if (path === "/permission")
  55. return json(route, typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? []))
  56. if (path === "/question")
  57. return json(route, typeof config.questions === "function" ? config.questions() : (config.questions ?? []))
  58. if (path === "/session/status") return json(route, config.sessionStatus ?? {})
  59. if (path === "/vcs/diff" && config.vcsDiff) return json(route, config.vcsDiff)
  60. if (path === "/file" && config.fileList)
  61. return json(route, await config.fileList(url.searchParams.get("path") ?? ""))
  62. if (path === "/file/content" && config.fileContent)
  63. return json(route, await config.fileContent(url.searchParams.get("path") ?? ""))
  64. if (path === "/find/file" && config.findFiles)
  65. return json(
  66. route,
  67. await config.findFiles({
  68. query: url.searchParams.get("query") ?? "",
  69. dirs: url.searchParams.get("dirs") ?? undefined,
  70. limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined,
  71. }),
  72. )
  73. if (path === "/api/reference")
  74. return json(route, {
  75. location: {
  76. directory: config.directory,
  77. project: { id: (config.project as { id?: string }).id, directory: config.directory },
  78. },
  79. data: [],
  80. })
  81. if (emptyObject.has(path)) return json(route, {})
  82. if (emptyList.has(path)) return json(route, [])
  83. if (path in staticRoutes) return json(route, staticRoutes[path])
  84. const sessionMatch = path.match(/^\/session\/([^/]+)$/)
  85. if (sessionMatch) {
  86. const session = config.sessions.find((s) => s.id === sessionMatch[1])
  87. return json(route, session ?? {})
  88. }
  89. const projectMatch = path.match(/^\/project\/([^/]+)$/)
  90. if (projectMatch) return json(route, config.project)
  91. const messageMatch = path.match(/^\/session\/([^/]+)\/message\/([^/]+)$/)
  92. if (messageMatch) {
  93. config.onMessage?.({ sessionID: messageMatch[1]!, messageID: messageMatch[2]! })
  94. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  95. const message = config.message?.(messageMatch[1]!, messageMatch[2]!)
  96. if (message === undefined) return json(route, { error: "Message not found" }, undefined, 404)
  97. return json(route, message)
  98. }
  99. if (/^\/session\/[^/]+\/(children|diff)$/.test(path)) return json(route, [])
  100. const messagesMatch = path.match(/^\/session\/([^/]+)\/message$/)
  101. if (messagesMatch) {
  102. const token = url.searchParams.get("before") ?? undefined
  103. const before = token ? cursors.get(token) : undefined
  104. if (token && !before) return json(route, { error: "Invalid cursor" }, undefined, 400)
  105. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "start" })
  106. await config.beforeMessagesResponse?.({ sessionID: messagesMatch[1]!, before })
  107. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  108. const limit = Number(url.searchParams.get("limit") ?? 80)
  109. const pageData = config.pageMessages(messagesMatch[1], limit, before)
  110. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "end" })
  111. if (!pageData.cursor) return json(route, pageData.items)
  112. const cursor = `cursor_${++nextCursor}`
  113. cursors.set(cursor, pageData.cursor)
  114. return json(route, pageData.items, { "x-next-cursor": cursor })
  115. }
  116. if (url.port === targetPort && targetPort !== appPort) return json(route, {})
  117. return route.fallback()
  118. })
  119. }
  120. function json(route: Route, body: unknown, headers?: Record<string, string>, status = 200) {
  121. return route.fulfill({
  122. status,
  123. contentType: "application/json",
  124. headers: {
  125. "access-control-allow-origin": "*",
  126. "access-control-expose-headers": "x-next-cursor",
  127. ...headers,
  128. },
  129. body: JSON.stringify(body ?? null),
  130. })
  131. }
  132. function sse(route: Route, events?: unknown[], retry?: number) {
  133. return route.fulfill({
  134. status: 200,
  135. contentType: "text/event-stream",
  136. body: `${retry === undefined ? "" : `retry: ${retry}\n\n`}${events?.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") || ": ok\n\n"}`,
  137. })
  138. }