mock-server.ts 4.8 KB

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