httpapi-v2-location.test.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import { afterEach, describe, expect, test } from "bun:test"
  2. import { EventV2 } from "@kirincode-ai/core/event"
  3. import { Location } from "@kirincode-ai/core/location"
  4. import { Context, Schema } from "effect"
  5. import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server"
  6. import { resetDatabase } from "../fixture/db"
  7. import { disposeAllInstances, tmpdir } from "../fixture/fixture"
  8. const context = Context.empty() as Context.Context<unknown>
  9. function request(route: string, directory: string, init: RequestInit = {}) {
  10. const headers = new Headers(init.headers)
  11. headers.set("x-opencode-directory", directory)
  12. return HttpApiApp.webHandler().handler(
  13. new Request(`http://localhost${route}`, {
  14. ...init,
  15. headers,
  16. }),
  17. context,
  18. )
  19. }
  20. const Event = Schema.Struct({
  21. id: EventV2.ID,
  22. type: Schema.String,
  23. location: Schema.optional(Location.Ref),
  24. data: Schema.Unknown,
  25. })
  26. async function* eventStream(body: ReadableStream<Uint8Array>) {
  27. const reader = body.getReader()
  28. const decoder = new TextDecoder()
  29. let buffer = ""
  30. try {
  31. while (true) {
  32. const boundary = buffer.match(/(?:\r\n|\r|\n){2}/)
  33. if (!boundary || boundary.index === undefined) {
  34. const value = await reader.read()
  35. if (value.done) return
  36. buffer += decoder.decode(value.value, { stream: true })
  37. continue
  38. }
  39. const record = buffer.slice(0, boundary.index)
  40. buffer = buffer.slice(boundary.index + boundary[0].length)
  41. const data = record
  42. .split(/\r\n|\r|\n/)
  43. .filter((line) => line.startsWith("data:"))
  44. .map((line) => line.slice(5).replace(/^ /, ""))
  45. if (data.length) yield Schema.decodeUnknownSync(Event)(JSON.parse(data.join("\n")))
  46. }
  47. } finally {
  48. try {
  49. await reader.cancel()
  50. } finally {
  51. reader.releaseLock()
  52. }
  53. }
  54. }
  55. async function readEvent(reader: AsyncIterator<typeof Event.Type>) {
  56. const value = await reader.next()
  57. if (value.done) throw new Error("event stream closed")
  58. return value.value
  59. }
  60. async function readEventType(reader: AsyncIterator<typeof Event.Type>, type: string) {
  61. for (let index = 0; index < 20; index++) {
  62. const event = await readEvent(reader)
  63. if (event.type === type) return event
  64. }
  65. throw new Error(`timed out waiting for ${type}`)
  66. }
  67. afterEach(async () => {
  68. await disposeAllInstances()
  69. await resetDatabase()
  70. })
  71. describe("v2 location HttpApi", () => {
  72. test("decodes EventV2 location refs without resolved project metadata", () => {
  73. expect(
  74. Schema.decodeUnknownSync(Event)({
  75. id: "evt_test",
  76. type: "file.watcher.updated",
  77. location: { directory: "/tmp/project" },
  78. data: {},
  79. }),
  80. ).toMatchObject({ location: { directory: "/tmp/project" } })
  81. })
  82. test("returns command and skill snapshots with resolved locations", async () => {
  83. await using tmp = await tmpdir({ git: true })
  84. for (const route of ["/api/command", "/api/skill"]) {
  85. const response = await request(route, tmp.path)
  86. expect(response.status).toBe(200)
  87. const body = (await response.json()) as {
  88. location: { directory: string; project: { id: string } }
  89. data: unknown
  90. }
  91. expect(body.data).toBeArray()
  92. expect(body.location.directory).toBe(tmp.path)
  93. expect(body.location.project.id).toBeTruthy()
  94. }
  95. })
  96. test("streams native EventV2 payloads across locations", async () => {
  97. await using subscriber = await tmpdir({ git: true })
  98. await using publisher = await tmpdir({ git: true })
  99. const response = await request("/api/event", subscriber.path)
  100. const reader = eventStream(response.body!)
  101. const connected = await readEvent(reader)
  102. expect(connected.type).toBe("server.connected")
  103. expect(connected.location).toBeUndefined()
  104. const created = await request("/session", publisher.path, { method: "POST" })
  105. expect(created.status).toBe(200)
  106. expect(await readEventType(reader, "session.created")).toMatchObject({
  107. type: "session.created",
  108. location: { directory: publisher.path },
  109. data: { sessionID: expect.any(String) },
  110. })
  111. await reader.return(undefined)
  112. })
  113. })