mock-server.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. protocol?: "v1" | "v2"
  6. provider: unknown
  7. directory: string
  8. project: unknown
  9. sessions: ({ id: string } & Record<string, unknown>)[]
  10. pageMessages: (sessionId: string, limit: number, before?: string) => { items: unknown[]; cursor?: string }
  11. vcsDiff?: unknown[]
  12. messageDelay?: number
  13. beforeMessagesResponse?: (input: { sessionID: string; before?: string }) => Promise<void>
  14. onMessages?: (input: { sessionID: string; before?: string; phase: "start" | "end" }) => void
  15. message?: (sessionID: string, messageID: string) => unknown
  16. onMessage?: (input: { sessionID: string; messageID: string }) => void
  17. events?: () => unknown[]
  18. eventRetry?: number
  19. todos?: (sessionID: string) => unknown[]
  20. permissions?: unknown[] | (() => unknown[])
  21. questions?: unknown[] | (() => unknown[])
  22. fileList?: (path: string) => unknown | Promise<unknown>
  23. fileContent?: (path: string) => unknown | Promise<unknown>
  24. findFiles?: (input: { query: string; dirs?: string; limit?: number }) => unknown
  25. sessionStatus?: Record<string, unknown> | (() => Record<string, unknown>)
  26. }
  27. export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
  28. const cursors = new Map<string, string>()
  29. let nextCursor = 0
  30. const staticRoutes: Record<string, unknown> = {
  31. "/provider": config.provider,
  32. "/path": {
  33. state: config.directory,
  34. config: config.directory,
  35. worktree: config.directory,
  36. directory: config.directory,
  37. home: "C:/OpenCode",
  38. },
  39. "/project": [config.project],
  40. "/project/current": config.project,
  41. "/agent": [{ name: "build", mode: "primary" }],
  42. "/vcs": { branch: "main", default_branch: "main" },
  43. "/session": config.sessions,
  44. }
  45. await page.route("**/*", async (route) => {
  46. const url = new URL(route.request().url())
  47. const targetPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
  48. const appPort = new URL(
  49. process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${process.env.PLAYWRIGHT_PORT ?? "3000"}`,
  50. ).port
  51. if (url.port !== targetPort && url.port !== appPort) return route.fallback()
  52. const path = url.pathname
  53. if (path === "/global/event" || path === "/event" || path === "/api/event") {
  54. const events = config.events?.()
  55. return sse(
  56. route,
  57. path === "/api/event"
  58. ? [{ id: "evt_mock_connected", type: "server.connected", data: {} }, ...(events?.map(currentEvent) ?? [])]
  59. : [
  60. ...(path === "/global/event"
  61. ? [{ payload: { id: "evt_mock_connected", type: "server.connected", properties: {} } }]
  62. : []),
  63. ...(events ?? []),
  64. ],
  65. config.eventRetry,
  66. )
  67. }
  68. if (path === "/global/health")
  69. return config.protocol === "v2" ? json(route, {}, undefined, 404) : json(route, { healthy: true })
  70. if (path === "/api/health" && config.protocol === "v2")
  71. return json(route, { healthy: true, version: "2.0.0", pid: 1 })
  72. if (path === "/experimental/capabilities") return json(route, { backgroundSubagents: true })
  73. if (path === "/permission")
  74. return json(route, typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? []))
  75. if (path === "/question")
  76. return json(route, typeof config.questions === "function" ? config.questions() : (config.questions ?? []))
  77. if (path === "/session/status")
  78. return json(
  79. route,
  80. typeof config.sessionStatus === "function" ? config.sessionStatus() : (config.sessionStatus ?? {}),
  81. )
  82. if (path === "/vcs/diff" && config.vcsDiff) return json(route, config.vcsDiff)
  83. if (path === "/file" && config.fileList)
  84. return json(route, await config.fileList(url.searchParams.get("path") ?? ""))
  85. if (path === "/file/content" && config.fileContent)
  86. return json(route, await config.fileContent(url.searchParams.get("path") ?? ""))
  87. if (path === "/find/file" && config.findFiles)
  88. return json(
  89. route,
  90. await config.findFiles({
  91. query: url.searchParams.get("query") ?? "",
  92. dirs: url.searchParams.get("dirs") ?? undefined,
  93. limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined,
  94. }),
  95. )
  96. if (path === "/api/reference")
  97. return json(route, {
  98. location: {
  99. directory: config.directory,
  100. project: { id: (config.project as { id?: string }).id, directory: config.directory },
  101. },
  102. data: [],
  103. })
  104. if (path === "/api/agent")
  105. return json(route, {
  106. location: location(config),
  107. data: [
  108. {
  109. id: "build",
  110. name: "Build",
  111. mode: "primary",
  112. hidden: false,
  113. request: { settings: {}, headers: {}, body: {} },
  114. permissions: [],
  115. },
  116. ],
  117. })
  118. if (path === "/api/command") return json(route, { location: location(config), data: [] })
  119. if (path === "/api/mcp") return json(route, { location: location(config), data: [] })
  120. if (path === "/api/mcp/resource")
  121. return json(route, { location: location(config), data: { resources: [], templates: [] } })
  122. const integration = path.match(/^\/api\/integration\/([^/]+)$/)?.[1]
  123. if (integration && route.request().method() === "GET")
  124. return json(route, {
  125. location: location(config),
  126. data: { id: integration, name: integration, methods: [{ type: "key", label: "API key" }], connections: [] },
  127. })
  128. if (/^\/api\/integration\/[^/]+\/connect\/key$/.test(path) && route.request().method() === "POST")
  129. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  130. if (path === "/api/project") return json(route, [config.project])
  131. if (path === "/api/project/current")
  132. return json(route, { id: (config.project as { id?: string }).id, directory: config.directory })
  133. if (path.startsWith("/api/project/") && route.request().method() === "PATCH") return json(route, config.project)
  134. if (path === "/api/path")
  135. return json(route, {
  136. state: config.directory,
  137. config: config.directory,
  138. worktree: config.directory,
  139. directory: config.directory,
  140. home: "C:/OpenCode",
  141. })
  142. if (path === "/api/permission/request")
  143. return json(route, {
  144. location: location(config),
  145. data: (typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? [])).map(
  146. currentPermission,
  147. ),
  148. })
  149. if (path === "/api/question/request")
  150. return json(route, {
  151. location: location(config),
  152. data: typeof config.questions === "function" ? config.questions() : (config.questions ?? []),
  153. })
  154. if (path === "/api/vcs")
  155. return json(route, { location: location(config), data: { branch: "main", defaultBranch: "main" } })
  156. if (path === "/api/vcs/status") return json(route, { location: location(config), data: [] })
  157. if (path === "/api/vcs/diff") return json(route, { location: location(config), data: config.vcsDiff ?? [] })
  158. if (path === "/api/pty/shells") return json(route, { location: location(config), data: [] })
  159. if (/^\/api\/pty\/[^/]+\/connect-token$/.test(path))
  160. return json(route, { location: location(config), data: { ticket: "e2e-ticket", expires_in: 60 } })
  161. if (emptyObject.has(path)) return json(route, {})
  162. if (emptyList.has(path)) return json(route, [])
  163. if (path === "/api/session") {
  164. const directory = url.searchParams.get("directory")
  165. const parentID = url.searchParams.get("parentID")
  166. const limit = Number(url.searchParams.get("limit") ?? 50)
  167. const offset = Number(url.searchParams.get("cursor") ?? 0)
  168. const sessions = config.sessions
  169. .filter((session) => !directory || session.directory === directory)
  170. .filter((session) => parentID !== "null" || session.parentID === undefined)
  171. .filter((session) => {
  172. const search = url.searchParams.get("search")?.toLowerCase()
  173. return (
  174. !search ||
  175. String(session.title ?? "")
  176. .toLowerCase()
  177. .includes(search)
  178. )
  179. })
  180. const ordered = url.searchParams.get("order") === "asc" ? sessions.toReversed() : sessions
  181. const data = ordered.slice(offset, offset + limit)
  182. const next = offset + limit < ordered.length ? String(offset + limit) : undefined
  183. return json(route, {
  184. data: data.map((session) => currentSession(session, config.directory)),
  185. cursor: { next },
  186. })
  187. }
  188. if (path === "/api/session/active") {
  189. const statuses = (config.sessionStatus ?? {}) as Record<string, { type?: string }>
  190. return json(route, {
  191. data: Object.fromEntries(
  192. Object.entries(statuses).flatMap(([id, status]) =>
  193. status.type === "idle" ? [] : [[id, { type: "running" }]],
  194. ),
  195. ),
  196. })
  197. }
  198. if (/^\/api\/session\/[^/]+\/shell$/.test(path) && route.request().method() === "POST") {
  199. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  200. }
  201. if (/^\/api\/session\/[^/]+\/question\/[^/]+\/(reply|reject)$/.test(path) && route.request().method() === "POST") {
  202. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  203. }
  204. if (/^\/api\/session\/[^/]+\/permission\/[^/]+\/reply$/.test(path) && route.request().method() === "POST") {
  205. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  206. }
  207. if (/^\/question\/[^/]+\/(reply|reject)$/.test(path) && route.request().method() === "POST") {
  208. return json(route, true)
  209. }
  210. if (/^\/session\/[^/]+\/permissions\/[^/]+$/.test(path) && route.request().method() === "POST") {
  211. return json(route, true)
  212. }
  213. if (
  214. /^\/api\/session\/[^/]+\/(archive|rename|interrupt|revert\/clear|revert\/commit)$/.test(path) &&
  215. route.request().method() === "POST"
  216. ) {
  217. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  218. }
  219. if (/^\/api\/session\/[^/]+$/.test(path) && route.request().method() === "DELETE") {
  220. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  221. }
  222. if (path in staticRoutes) return json(route, staticRoutes[path])
  223. const currentSessionMatch = path.match(/^\/api\/session\/([^/]+)$/)
  224. if (currentSessionMatch) {
  225. const session = config.sessions.find((item) => item.id === currentSessionMatch[1])
  226. if (!session) return json(route, { error: "Session not found" }, undefined, 404)
  227. return json(route, {
  228. data: currentSession(session, config.directory),
  229. })
  230. }
  231. const sessionMatch = path.match(/^\/session\/([^/]+)$/)
  232. if (sessionMatch) {
  233. const session = config.sessions.find((s) => s.id === sessionMatch[1])
  234. return json(route, session ?? {})
  235. }
  236. const projectMatch = path.match(/^\/project\/([^/]+)$/)
  237. if (projectMatch) return json(route, config.project)
  238. const messageMatch = path.match(/^\/session\/([^/]+)\/message\/([^/]+)$/)
  239. if (messageMatch) {
  240. config.onMessage?.({ sessionID: messageMatch[1]!, messageID: messageMatch[2]! })
  241. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  242. const message = config.message?.(messageMatch[1]!, messageMatch[2]!)
  243. if (message === undefined) return json(route, { error: "Message not found" }, undefined, 404)
  244. return json(route, message)
  245. }
  246. const todoMatch = path.match(/^\/session\/([^/]+)\/todo$/)
  247. if (todoMatch) return json(route, config.todos?.(todoMatch[1]!) ?? [])
  248. if (/^\/session\/[^/]+\/(children|diff)$/.test(path)) return json(route, [])
  249. const currentMessagesMatch = path.match(/^\/api\/session\/([^/]+)\/message$/)
  250. if (currentMessagesMatch) {
  251. const token = url.searchParams.get("cursor") ?? undefined
  252. const before = token ? cursors.get(token) : undefined
  253. if (token && !before) return json(route, { error: "Invalid cursor" }, undefined, 400)
  254. config.onMessages?.({ sessionID: currentMessagesMatch[1], before, phase: "start" })
  255. await config.beforeMessagesResponse?.({ sessionID: currentMessagesMatch[1]!, before })
  256. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  257. const pageData = config.pageMessages(currentMessagesMatch[1], Number(url.searchParams.get("limit") ?? 50), before)
  258. config.onMessages?.({ sessionID: currentMessagesMatch[1], before, phase: "end" })
  259. const cursor = pageData.cursor ? `cursor_${++nextCursor}` : undefined
  260. if (cursor) cursors.set(cursor, pageData.cursor!)
  261. return json(route, {
  262. data: pageData.items.map(currentMessage).reverse(),
  263. cursor: { next: cursor },
  264. })
  265. }
  266. const messagesMatch = path.match(/^\/session\/([^/]+)\/message$/)
  267. if (messagesMatch) {
  268. const token = url.searchParams.get("before") ?? undefined
  269. const before = token ? cursors.get(token) : undefined
  270. if (token && !before) return json(route, { error: "Invalid cursor" }, undefined, 400)
  271. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "start" })
  272. await config.beforeMessagesResponse?.({ sessionID: messagesMatch[1]!, before })
  273. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  274. const limit = Number(url.searchParams.get("limit") ?? 80)
  275. const pageData = config.pageMessages(messagesMatch[1], limit, before)
  276. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "end" })
  277. if (!pageData.cursor) return json(route, pageData.items)
  278. const cursor = `cursor_${++nextCursor}`
  279. cursors.set(cursor, pageData.cursor)
  280. return json(route, pageData.items, { "x-next-cursor": cursor })
  281. }
  282. if (url.port === targetPort && targetPort !== appPort) return json(route, {})
  283. return route.fallback()
  284. })
  285. }
  286. function location(config: MockServerConfig) {
  287. return {
  288. directory: config.directory,
  289. project: { id: (config.project as { id?: string }).id, directory: config.directory },
  290. }
  291. }
  292. function currentPermission(value: unknown) {
  293. const permission = value as Record<string, unknown>
  294. if (permission.action) return permission
  295. const tool = permission.tool as { messageID?: string; callID?: string } | undefined
  296. return {
  297. id: permission.id,
  298. sessionID: permission.sessionID,
  299. action: permission.permission,
  300. resources: permission.patterns ?? [],
  301. save: permission.always,
  302. metadata: permission.metadata,
  303. source:
  304. tool?.messageID && tool.callID ? { type: "tool", messageID: tool.messageID, callID: tool.callID } : undefined,
  305. }
  306. }
  307. export function currentSession(session: { id: string } & Record<string, unknown>, fallbackDirectory?: string) {
  308. const time = session.time && typeof session.time === "object" ? session.time : {}
  309. return {
  310. id: session.id,
  311. parentID: session.parentID,
  312. projectID: session.projectID ?? "project",
  313. agent: session.agent ?? "build",
  314. model: session.model ?? { id: "mock-model", providerID: "mock-provider" },
  315. cost: session.cost ?? 0,
  316. tokens: session.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  317. time: {
  318. created: "created" in time && typeof time.created === "number" ? time.created : 0,
  319. updated: "updated" in time && typeof time.updated === "number" ? time.updated : 0,
  320. ...(session.time && typeof session.time === "object" && "archived" in session.time
  321. ? { archived: session.time.archived }
  322. : {}),
  323. },
  324. title: session.title ?? session.id,
  325. location: {
  326. directory: typeof session.directory === "string" ? session.directory : fallbackDirectory,
  327. ...(typeof session.workspaceID === "string" ? { workspaceID: session.workspaceID } : {}),
  328. },
  329. subpath: session.path,
  330. revert: session.revert,
  331. }
  332. }
  333. function currentMessage(value: unknown) {
  334. const item = value as {
  335. info: Record<string, unknown> & { id: string; role: "user" | "assistant"; time: { created: number } }
  336. parts: Array<Record<string, unknown> & { type: string }>
  337. }
  338. if (item.info.role === "user") {
  339. return {
  340. id: item.info.id,
  341. type: "user",
  342. time: item.info.time,
  343. text: item.parts
  344. .flatMap((part) => (part.type === "text" && typeof part.text === "string" ? [part.text] : []))
  345. .join("\n"),
  346. }
  347. }
  348. return {
  349. id: item.info.id,
  350. type: "assistant",
  351. time: item.info.time,
  352. agent: item.info.agent ?? "build",
  353. model: { id: item.info.modelID ?? "model", providerID: item.info.providerID ?? "provider" },
  354. cost: item.info.cost,
  355. tokens: item.info.tokens,
  356. error: item.info.error,
  357. content: item.parts.flatMap<unknown>((part) => {
  358. if (part.type === "text" || part.type === "reasoning") return [{ type: part.type, text: part.text ?? "" }]
  359. if (part.type !== "tool") return []
  360. const state = part.state as Record<string, unknown>
  361. return [
  362. {
  363. type: "tool",
  364. id: part.id,
  365. name: part.tool,
  366. time: state.time ?? { created: item.info.time.created },
  367. state:
  368. state.status === "pending"
  369. ? { status: "streaming", input: state.raw ?? JSON.stringify(state.input ?? {}) }
  370. : state.status === "completed"
  371. ? {
  372. status: "completed",
  373. input: state.input ?? {},
  374. structured: state.metadata ?? {},
  375. content: [{ type: "text", text: state.output ?? "" }],
  376. }
  377. : state.status === "error"
  378. ? {
  379. status: "error",
  380. input: state.input ?? {},
  381. structured: state.metadata ?? {},
  382. content: [],
  383. error: { type: "ToolError", message: state.error ?? "Tool failed" },
  384. }
  385. : { status: "running", input: state.input ?? {}, structured: state.metadata ?? {}, content: [] },
  386. },
  387. ]
  388. }),
  389. }
  390. }
  391. function json(route: Route, body: unknown, headers?: Record<string, string>, status = 200) {
  392. return route.fulfill({
  393. status,
  394. contentType: "application/json",
  395. headers: {
  396. "access-control-allow-origin": "*",
  397. "access-control-expose-headers": "x-next-cursor",
  398. ...headers,
  399. },
  400. body: JSON.stringify(body ?? null),
  401. })
  402. }
  403. function sse(route: Route, events?: unknown[], retry?: number) {
  404. return route.fulfill({
  405. status: 200,
  406. contentType: "text/event-stream",
  407. body: `${retry === undefined ? "" : `retry: ${retry}\n\n`}${events?.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") || ": ok\n\n"}`,
  408. })
  409. }
  410. function currentEvent(input: unknown) {
  411. if (!input || typeof input !== "object" || !("payload" in input)) return input
  412. const envelope = input as { directory?: string; payload?: unknown }
  413. if (!envelope.payload || typeof envelope.payload !== "object") return input
  414. const payload = envelope.payload as { id?: string; type?: string; properties?: unknown }
  415. if (!payload.type) return input
  416. return {
  417. id: payload.id ?? `evt_mock_${Date.now()}`,
  418. created: Date.now(),
  419. type: payload.type,
  420. data: payload.properties ?? {},
  421. location: envelope.directory && envelope.directory !== "global" ? { directory: envelope.directory } : undefined,
  422. }
  423. }