mock-server.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import type { Page, Route } from "@playwright/test"
  2. const emptyList = new Set([
  3. "/skill",
  4. "/command",
  5. "/lsp",
  6. "/formatter",
  7. "/permission",
  8. "/question",
  9. "/vcs/status",
  10. "/vcs/diff",
  11. ])
  12. const emptyObject = new Set(["/global/config", "/config", "/provider/auth", "/mcp", "/session/status"])
  13. export interface MockServerConfig {
  14. provider: unknown
  15. directory: string
  16. project: unknown
  17. sessions: ({ id: string } & Record<string, unknown>)[]
  18. pageMessages: (sessionId: string, limit: number, before?: string) => { items: unknown[]; cursor?: string }
  19. messageDelay?: number
  20. onMessages?: (input: { sessionID: string; before?: string; phase: "start" | "end" }) => void
  21. events?: () => unknown[]
  22. eventRetry?: number
  23. }
  24. export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
  25. const staticRoutes: Record<string, unknown> = {
  26. "/provider": config.provider,
  27. "/path": {
  28. state: config.directory,
  29. config: config.directory,
  30. worktree: config.directory,
  31. directory: config.directory,
  32. home: "C:/OpenCode",
  33. },
  34. "/project": [config.project],
  35. "/project/current": config.project,
  36. "/agent": [{ name: "build", mode: "primary" }],
  37. "/vcs": { branch: "main", default_branch: "main" },
  38. "/session": config.sessions,
  39. }
  40. await page.route("**/*", async (route) => {
  41. const url = new URL(route.request().url())
  42. const targetPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
  43. const appPort = new URL(
  44. process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${process.env.PLAYWRIGHT_PORT ?? "3000"}`,
  45. ).port
  46. if (url.port !== targetPort && url.port !== appPort) return route.fallback()
  47. const path = url.pathname
  48. if (path === "/global/event" || path === "/event") return sse(route, config.events?.(), config.eventRetry)
  49. if (path === "/global/health") return json(route, { healthy: true })
  50. if (emptyObject.has(path)) return json(route, {})
  51. if (emptyList.has(path)) return json(route, [])
  52. if (path in staticRoutes) return json(route, staticRoutes[path])
  53. const sessionMatch = path.match(/^\/session\/([^/]+)$/)
  54. if (sessionMatch) {
  55. const session = config.sessions.find((s) => s.id === sessionMatch[1])
  56. return json(route, session ?? {})
  57. }
  58. if (/^\/session\/[^/]+\/(children|todo|diff)$/.test(path)) return json(route, [])
  59. const messagesMatch = path.match(/^\/session\/([^/]+)\/message$/)
  60. if (messagesMatch) {
  61. const before = url.searchParams.get("before") ?? undefined
  62. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "start" })
  63. if (config.messageDelay) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  64. const limit = Number(url.searchParams.get("limit") ?? 80)
  65. const pageData = config.pageMessages(messagesMatch[1], limit, before)
  66. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "end" })
  67. return json(route, pageData.items, pageData.cursor ? { "x-next-cursor": pageData.cursor } : undefined)
  68. }
  69. if (url.port === targetPort && targetPort !== appPort) return json(route, {})
  70. return route.fallback()
  71. })
  72. }
  73. function json(route: Route, body: unknown, headers?: Record<string, string>) {
  74. return route.fulfill({
  75. status: 200,
  76. contentType: "application/json",
  77. headers: {
  78. "access-control-allow-origin": "*",
  79. "access-control-expose-headers": "x-next-cursor",
  80. ...headers,
  81. },
  82. body: JSON.stringify(body ?? null),
  83. })
  84. }
  85. function sse(route: Route, events?: unknown[], retry?: number) {
  86. return route.fulfill({
  87. status: 200,
  88. contentType: "text/event-stream",
  89. body: `${retry === undefined ? "" : `retry: ${retry}\n\n`}${events?.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") || ": ok\n\n"}`,
  90. })
  91. }