promise.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import { expect, test } from "bun:test"
  2. import { isSessionNotFoundError, isUnauthorizedError, OpenCode } from "../src/promise/index"
  3. test("exposes every standard HTTP API group", () => {
  4. const client = OpenCode.make({ baseUrl: "http://localhost:3000" })
  5. expect(Object.keys(client)).toEqual([
  6. "health",
  7. "server",
  8. "location",
  9. "agent",
  10. "plugin",
  11. "session",
  12. "message",
  13. "model",
  14. "generate",
  15. "provider",
  16. "integration",
  17. "mcp",
  18. "credential",
  19. "project",
  20. "form",
  21. "permission",
  22. "file",
  23. "command",
  24. "skill",
  25. "event",
  26. "pty",
  27. "shell",
  28. "question",
  29. "reference",
  30. "projectCopy",
  31. "vcs",
  32. "debug",
  33. ])
  34. expect(Object.keys(client.debug)).toEqual(["location"])
  35. expect(Object.keys(client.debug.location)).toEqual(["list", "evict"])
  36. expect(Object.keys(client.message)).toEqual(["list"])
  37. expect(Object.keys(client.integration)).toEqual(["list", "get", "wellknown", "connect", "oauth", "command"])
  38. expect(Object.keys(client.integration.wellknown)).toEqual(["add"])
  39. expect(Object.keys(client.integration.connect)).toEqual(["key"])
  40. expect(Object.keys(client.integration.oauth)).toEqual(["connect", "status", "complete", "cancel"])
  41. expect(Object.keys(client.integration.command)).toEqual(["connect", "status", "cancel"])
  42. expect(Object.keys(client.file)).toEqual(["read", "list", "find"])
  43. expect(Object.keys(client.vcs)).toEqual(["status", "diff"])
  44. expect(Object.keys(client.pty)).toEqual(["list", "create", "get", "update", "remove"])
  45. expect(Object.keys(client.shell)).toEqual(["list", "create", "get", "timeout", "output", "remove"])
  46. expect(Object.keys(client.project)).toEqual(["list", "current", "directories"])
  47. })
  48. test("server.get uses the public HTTP contract", async () => {
  49. let request: Request | undefined
  50. const client = OpenCode.make({
  51. baseUrl: "http://localhost:3000",
  52. fetch: async (input) => {
  53. request = input instanceof Request ? input : new Request(input)
  54. return Response.json({ urls: ["http://192.168.1.10:4096"] })
  55. },
  56. })
  57. expect(await client.server.get()).toEqual({ urls: ["http://192.168.1.10:4096"] })
  58. expect(request?.method).toBe("GET")
  59. expect(request?.url).toBe("http://localhost:3000/api/server")
  60. })
  61. test("experimental wellknown integration add uses the public HTTP contract", async () => {
  62. let request: Request | undefined
  63. const client = OpenCode.make({
  64. baseUrl: "http://localhost:3000",
  65. fetch: async (input, init) => {
  66. request = input instanceof Request ? input : new Request(input, init)
  67. return new Response(null, { status: 204 })
  68. },
  69. })
  70. await client.integration.wellknown.add({
  71. url: "https://example.com",
  72. location: { directory: "/tmp/project" },
  73. })
  74. expect(request?.method).toBe("POST")
  75. expect(request?.url).toBe(
  76. "http://localhost:3000/api/experimental/integration/wellknown?location%5Bdirectory%5D=%2Ftmp%2Fproject",
  77. )
  78. expect(await request?.json()).toEqual({ url: "https://example.com" })
  79. })
  80. test("health.stop sends exact replacement identity", async () => {
  81. let request: Request | undefined
  82. const client = OpenCode.make({
  83. baseUrl: "http://localhost:3000",
  84. fetch: async (input, init) => {
  85. request = input instanceof Request ? input : new Request(input, init)
  86. return Response.json({ accepted: true })
  87. },
  88. })
  89. expect(await client.health.stop({ instanceID: "instance" })).toEqual({ accepted: true })
  90. expect(request?.method).toBe("POST")
  91. expect(request?.url).toBe("http://localhost:3000/api/service/stop")
  92. expect(await request?.json()).toEqual({ instanceID: "instance" })
  93. })
  94. test("MCP resource catalog uses the public HTTP contract", async () => {
  95. let request: Request | undefined
  96. const client = OpenCode.make({
  97. baseUrl: "http://localhost:3000",
  98. fetch: async (input) => {
  99. request = input instanceof Request ? input : new Request(input)
  100. return Response.json({
  101. location: { directory: "/tmp/project", project: { id: "proj_test", directory: "/tmp/project" } },
  102. data: {
  103. resources: [{ server: "docs", name: "Readme", uri: "docs://readme" }],
  104. templates: [{ server: "docs", name: "File", uriTemplate: "docs://{path}" }],
  105. },
  106. })
  107. },
  108. })
  109. const result = await client.mcp.resource.catalog({ location: { directory: "/tmp/project" } })
  110. expect(result.data.resources[0]?.uri).toBe("docs://readme")
  111. expect(request?.method).toBe("GET")
  112. expect(request?.url).toBe("http://localhost:3000/api/mcp/resource?location%5Bdirectory%5D=%2Ftmp%2Fproject")
  113. })
  114. test("file.read returns binary content from the public HTTP contract", async () => {
  115. let request: Request | undefined
  116. const client = OpenCode.make({
  117. baseUrl: "http://localhost:3000",
  118. fetch: async (input) => {
  119. request = input instanceof Request ? input : new Request(input)
  120. return new Response(new Uint8Array([104, 105]))
  121. },
  122. })
  123. const content = await client.file.read({
  124. path: "src/a b#c.ts",
  125. location: { directory: "/tmp/project" },
  126. })
  127. expect(Array.from(content)).toEqual([104, 105])
  128. expect(request?.url).toBe(
  129. "http://localhost:3000/api/fs/read/src/a%20b%23c.ts?location%5Bdirectory%5D=%2Ftmp%2Fproject",
  130. )
  131. })
  132. test("project methods use the public HTTP contract", async () => {
  133. const requests: string[] = []
  134. const client = OpenCode.make({
  135. baseUrl: "http://localhost:3000",
  136. fetch: async (input) => {
  137. const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
  138. requests.push(url)
  139. if (url.includes("/directories")) return Response.json([])
  140. return Response.json({ id: "proj_test", directory: "/tmp/project" })
  141. },
  142. })
  143. const current = await client.project.current({ location: { workspace: "wrk_test" } })
  144. const directories = await client.project.directories({
  145. projectID: current.id,
  146. location: { directory: current.directory },
  147. })
  148. expect(current).toEqual({ id: "proj_test", directory: "/tmp/project" })
  149. expect(directories).toEqual([])
  150. expect(requests).toEqual([
  151. "http://localhost:3000/api/project/current?location%5Bworkspace%5D=wrk_test",
  152. "http://localhost:3000/api/project/proj_test/directories?location%5Bdirectory%5D=%2Ftmp%2Fproject",
  153. ])
  154. })
  155. test("shell list and remove use the public HTTP contract", async () => {
  156. const requests: Array<{ method: string; url: string }> = []
  157. const shell = {
  158. id: "sh_test",
  159. status: "running",
  160. command: "pwd",
  161. cwd: "/tmp/project",
  162. shell: "/bin/zsh",
  163. file: "/tmp/opencode-shell",
  164. metadata: { sessionID: "ses_test" },
  165. time: { started: 1_717_171_717_000 },
  166. }
  167. const client = OpenCode.make({
  168. baseUrl: "http://localhost:3000",
  169. fetch: async (input, init) => {
  170. const request = input instanceof Request ? input : new Request(input, init)
  171. requests.push({ method: request.method, url: request.url })
  172. if (request.method === "DELETE") return new Response(null, { status: 204 })
  173. return Response.json({
  174. location: { directory: "/tmp/project", project: { id: "proj_test", directory: "/tmp/project" } },
  175. data: [shell],
  176. })
  177. },
  178. })
  179. const result = await client.shell.list({ location: { directory: "/tmp/project" } })
  180. await client.shell.remove({ id: shell.id })
  181. expect(result.data).toEqual([shell])
  182. expect(requests).toEqual([
  183. { method: "GET", url: "http://localhost:3000/api/shell?location%5Bdirectory%5D=%2Ftmp%2Fproject" },
  184. { method: "DELETE", url: "http://localhost:3000/api/shell/sh_test" },
  185. ])
  186. })
  187. test("session.get returns the wire projection", async () => {
  188. const client = OpenCode.make({
  189. baseUrl: "http://localhost:3000",
  190. fetch: async (input) => {
  191. expect(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).toBe(
  192. "http://localhost:3000/api/session/ses_test",
  193. )
  194. return Response.json(session)
  195. },
  196. })
  197. const result = await client.session.get({ sessionID: "ses_test" })
  198. expect(result.time.created).toBe(1_717_171_717_000)
  199. })
  200. test("session instructions methods use the public HTTP contract", async () => {
  201. const requests: Array<{ method: string; url: string; body?: unknown }> = []
  202. const instructions = [{ key: "review-notes", value: { text: "Check the diff", priority: 1 } }]
  203. const client = OpenCode.make({
  204. baseUrl: "http://localhost:3000",
  205. fetch: async (input, init) => {
  206. const request = input instanceof Request ? input : new Request(input, init)
  207. requests.push({
  208. method: request.method,
  209. url: request.url,
  210. body: request.method === "PUT" ? await request.json() : undefined,
  211. })
  212. if (request.method === "GET") return Response.json({ data: instructions })
  213. return new Response(null, { status: 204 })
  214. },
  215. })
  216. const result = await client.session.instructions.entry.list({ sessionID: "ses_test" })
  217. await client.session.instructions.entry.put({
  218. sessionID: "ses_test",
  219. key: "review-notes",
  220. value: instructions[0].value,
  221. })
  222. await client.session.instructions.entry.remove({ sessionID: "ses_test", key: "review-notes" })
  223. expect(result).toEqual(instructions)
  224. expect(requests).toEqual([
  225. {
  226. method: "GET",
  227. url: "http://localhost:3000/api/session/ses_test/instructions/entries",
  228. body: undefined,
  229. },
  230. {
  231. method: "PUT",
  232. url: "http://localhost:3000/api/session/ses_test/instructions/entries/review-notes",
  233. body: { value: { text: "Check the diff", priority: 1 } },
  234. },
  235. {
  236. method: "DELETE",
  237. url: "http://localhost:3000/api/session/ses_test/instructions/entries/review-notes",
  238. body: undefined,
  239. },
  240. ])
  241. })
  242. test("session.pending.list uses the public HTTP contract", async () => {
  243. const requests: Array<{ method: string; url: string }> = []
  244. const pending = [
  245. {
  246. admittedSeq: 3,
  247. id: "msg_pending",
  248. sessionID: "ses_test",
  249. timeCreated: 1_717_171_717_000,
  250. type: "user",
  251. data: { text: "Fix the failing tests" },
  252. delivery: "steer",
  253. },
  254. ]
  255. const client = OpenCode.make({
  256. baseUrl: "http://localhost:3000",
  257. fetch: async (input, init) => {
  258. const request = input instanceof Request ? input : new Request(input, init)
  259. requests.push({ method: request.method, url: request.url })
  260. return Response.json({ data: pending })
  261. },
  262. })
  263. const result = await client.session.pending.list({ sessionID: "ses_test" })
  264. expect(result).toEqual(pending)
  265. expect(requests).toEqual([{ method: "GET", url: "http://localhost:3000/api/session/ses_test/pending" }])
  266. })
  267. test("event.subscribe exposes the Promise event stream wire projection", async () => {
  268. const client = OpenCode.make({
  269. baseUrl: "http://localhost:3000",
  270. fetch: async () =>
  271. new Response(
  272. `: heartbeat\n\ndata: ${JSON.stringify({ id: "evt_connected", created: 0, type: "server.connected", data: {} })}\n\n` +
  273. `data: ${JSON.stringify(modelSwitchedEvent)}\n\n`,
  274. { headers: { "content-type": "text/event-stream" } },
  275. ),
  276. })
  277. const events = []
  278. for await (const event of client.event.subscribe()) events.push(event)
  279. expect(events).toEqual([{ id: "evt_connected", created: 0, type: "server.connected", data: {} }, modelSwitchedEvent])
  280. expect(events[1]?.type === "session.model.selected" && events[1].created).toBe(1_717_171_717_000)
  281. })
  282. test("event.subscribe terminates on malformed Promise SSE data", async () => {
  283. const client = OpenCode.make({
  284. baseUrl: "http://localhost:3000",
  285. fetch: async () => new Response("data: {not-json}\n\n", { headers: { "content-type": "text/event-stream" } }),
  286. })
  287. await expect(client.event.subscribe()[Symbol.asyncIterator]().next()).rejects.toMatchObject({
  288. name: "ClientError",
  289. reason: "MalformedResponse",
  290. })
  291. })
  292. test("event.subscribe accepts a fragmented SSE event below the size limit", async () => {
  293. const event = { id: "evt_large", type: "test.large", data: { output: "x".repeat(12 * 1024 * 1024) } }
  294. const encoded = new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`)
  295. const client = OpenCode.make({
  296. baseUrl: "http://localhost:3000",
  297. fetch: async () =>
  298. new Response(
  299. new ReadableStream({
  300. start(controller) {
  301. for (let offset = 0; offset < encoded.length; offset += 64 * 1024) {
  302. controller.enqueue(encoded.slice(offset, offset + 64 * 1024))
  303. }
  304. controller.close()
  305. },
  306. }),
  307. { headers: { "content-type": "text/event-stream" } },
  308. ),
  309. })
  310. await expect(client.event.subscribe()[Symbol.asyncIterator]().next()).resolves.toEqual({ done: false, value: event })
  311. })
  312. test("event.subscribe rejects an SSE event above the size limit", async () => {
  313. const client = OpenCode.make({
  314. baseUrl: "http://localhost:3000",
  315. fetch: async () =>
  316. new Response(`data: ${JSON.stringify({ output: "x".repeat(16 * 1024 * 1024) })}`, {
  317. headers: { "content-type": "text/event-stream" },
  318. }),
  319. })
  320. await expect(client.event.subscribe()[Symbol.asyncIterator]().next()).rejects.toMatchObject({
  321. name: "ClientError",
  322. reason: "SseEventTooLarge",
  323. })
  324. })
  325. test("session methods use the public HTTP contract", async () => {
  326. const requests: Array<{ url: string; init?: RequestInit }> = []
  327. const client = OpenCode.make({
  328. baseUrl: "http://localhost:3000",
  329. fetch: async (input, init) => {
  330. const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
  331. requests.push({ url, init })
  332. if (url.includes("/event")) {
  333. return new Response(`data: ${JSON.stringify(modelSwitchedEvent)}\n\n`, {
  334. headers: { "content-type": "text/event-stream" },
  335. })
  336. }
  337. if (url.includes("/log")) {
  338. return new Response(`data: ${JSON.stringify(modelSwitchedEvent)}\n\ndata: ${JSON.stringify(synced)}\n\n`, {
  339. headers: { "content-type": "text/event-stream" },
  340. })
  341. }
  342. if (url.includes("/prompt")) return Response.json(admission)
  343. if (url.includes("/synthetic")) return Response.json(syntheticAdmission)
  344. if (url.endsWith("/compact")) return Response.json(compactionAdmission)
  345. if (url.includes("/context")) return Response.json({ data: [] })
  346. if (url.includes("/message/")) return Response.json({ data: modelSwitchedMessage })
  347. if (url.endsWith("/api/session/active")) return Response.json({ data: { ses_test: { type: "running" } } })
  348. if (init?.method === "POST" && url.endsWith("/api/session")) return Response.json(session)
  349. if (init?.method === "POST") return new Response(null, { status: 204 })
  350. return Response.json({ data: [session.data], cursor: { next: "next" } })
  351. },
  352. })
  353. const page = await client.session.list({ limit: 10, order: "desc", parentID: null })
  354. const active = await client.session.active()
  355. const created = await client.session.create({ location: { directory: "/tmp/project" } })
  356. await client.session.switchAgent({ sessionID: "ses_test", agent: "build" })
  357. await client.session.switchModel({
  358. sessionID: "ses_test",
  359. model: { id: "claude", providerID: "anthropic" },
  360. })
  361. const admitted = await client.session.prompt({
  362. sessionID: "ses_test",
  363. text: "Hello",
  364. resume: false,
  365. })
  366. const synthetic = await client.session.synthetic({
  367. sessionID: "ses_test",
  368. text: "Completed",
  369. delivery: "queue",
  370. resume: false,
  371. })
  372. await client.session.compact({ sessionID: "ses_test" })
  373. await client.session.wait({ sessionID: "ses_test" })
  374. const context = await client.session.context({ sessionID: "ses_test" })
  375. const log = []
  376. for await (const item of client.session.log({ sessionID: "ses_test", after: 0 })) log.push(item)
  377. await client.session.interrupt({ sessionID: "ses_test" })
  378. const message = await client.session.message({ sessionID: "ses_test", messageID: "msg_model" })
  379. expect(page.cursor.next).toBe("next")
  380. expect(active).toEqual({ ses_test: { type: "running" } })
  381. expect(created.id).toBe("ses_test")
  382. expect(admitted.id).toBe("msg_test")
  383. expect(synthetic).toMatchObject({ type: "synthetic", data: { text: "Completed" }, delivery: "queue" })
  384. expect(context).toEqual([])
  385. expect(log).toEqual([modelSwitchedEvent, synced])
  386. expect(message).toEqual(modelSwitchedMessage)
  387. expect(requests.map((request) => [request.init?.method, request.url])).toEqual([
  388. ["GET", "http://localhost:3000/api/session?limit=10&order=desc&parentID=null"],
  389. ["GET", "http://localhost:3000/api/session/active"],
  390. ["POST", "http://localhost:3000/api/session"],
  391. ["POST", "http://localhost:3000/api/session/ses_test/agent"],
  392. ["POST", "http://localhost:3000/api/session/ses_test/model"],
  393. ["POST", "http://localhost:3000/api/session/ses_test/prompt"],
  394. ["POST", "http://localhost:3000/api/session/ses_test/synthetic"],
  395. ["POST", "http://localhost:3000/api/session/ses_test/compact"],
  396. ["POST", "http://localhost:3000/api/session/ses_test/wait"],
  397. ["GET", "http://localhost:3000/api/session/ses_test/context"],
  398. ["GET", "http://localhost:3000/api/experimental/session/ses_test/log?after=0"],
  399. ["POST", "http://localhost:3000/api/session/ses_test/interrupt"],
  400. ["GET", "http://localhost:3000/api/session/ses_test/message/msg_model"],
  401. ])
  402. const body = requests.find((request) => request.url.endsWith("/api/session/ses_test/prompt"))?.init?.body
  403. if (typeof body !== "string") throw new Error("Expected JSON request body")
  404. expect(JSON.parse(body)).toEqual({
  405. text: "Hello",
  406. resume: false,
  407. })
  408. const syntheticBody = requests.find((request) => request.url.endsWith("/synthetic"))?.init?.body
  409. if (typeof syntheticBody !== "string") throw new Error("Expected JSON synthetic request body")
  410. expect(JSON.parse(syntheticBody)).toEqual({
  411. text: "Completed",
  412. delivery: "queue",
  413. resume: false,
  414. })
  415. })
  416. test("middleware errors remain declared client errors", async () => {
  417. const client = OpenCode.make({
  418. baseUrl: "http://localhost:3000",
  419. fetch: async () =>
  420. Response.json({ _tag: "UnauthorizedError", message: "Authentication required" }, { status: 401 }),
  421. })
  422. try {
  423. await client.session.create({})
  424. throw new Error("Expected request to fail")
  425. } catch (error) {
  426. expect(isUnauthorizedError(error)).toBe(true)
  427. }
  428. })
  429. test("session.log decodes SessionNotFoundError", async () => {
  430. const client = OpenCode.make({
  431. baseUrl: "http://localhost:3000",
  432. fetch: async () =>
  433. Response.json(
  434. { _tag: "SessionNotFoundError", sessionID: "ses_missing", message: "Session not found" },
  435. { status: 404 },
  436. ),
  437. })
  438. try {
  439. await client.session.log({ sessionID: "ses_missing" })[Symbol.asyncIterator]().next()
  440. throw new Error("Expected request to fail")
  441. } catch (error) {
  442. expect(isSessionNotFoundError(error)).toBe(true)
  443. }
  444. })
  445. const session = {
  446. data: {
  447. id: "ses_test",
  448. projectID: "project",
  449. cost: 0,
  450. tokens: {
  451. input: 1,
  452. output: 2,
  453. reasoning: 3,
  454. cache: { read: 4, write: 5 },
  455. },
  456. time: {
  457. created: 1_717_171_717_000,
  458. updated: 1_717_171_717_000,
  459. },
  460. title: "Test",
  461. location: { directory: "/tmp/project" },
  462. },
  463. }
  464. const admission = {
  465. data: {
  466. admittedSeq: 0,
  467. id: "msg_test",
  468. sessionID: "ses_test",
  469. type: "user",
  470. data: { text: "Hello" },
  471. delivery: "steer",
  472. timeCreated: 1_717_171_717_000,
  473. },
  474. }
  475. const syntheticAdmission = {
  476. data: {
  477. admittedSeq: 1,
  478. id: "msg_synthetic",
  479. sessionID: "ses_test",
  480. type: "synthetic",
  481. data: { text: "Completed" },
  482. delivery: "queue",
  483. timeCreated: 1_717_171_717_000,
  484. },
  485. }
  486. const compactionAdmission = {
  487. data: {
  488. type: "compaction",
  489. admittedSeq: 1,
  490. id: "msg_compaction",
  491. sessionID: "ses_test",
  492. timeCreated: 1_717_171_717_000,
  493. },
  494. }
  495. const modelSwitchedMessage = {
  496. id: "msg_model",
  497. type: "model-switched",
  498. time: { created: 1_717_171_717_000 },
  499. model: { id: "claude", providerID: "anthropic" },
  500. }
  501. const synced = { type: "log.synced", aggregateID: "ses_test", seq: 1 }
  502. const modelSwitchedEvent = {
  503. id: "evt_model",
  504. created: 1_717_171_717_000,
  505. type: "session.model.selected",
  506. durable: { aggregateID: "ses_test", seq: 1, version: 1 },
  507. data: {
  508. sessionID: "ses_test",
  509. model: { id: "claude", providerID: "anthropic" },
  510. },
  511. }