mock-server.ts 20 KB

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