integration.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { describe, expect } from "bun:test"
  2. import { Duration, Effect, Exit, Fiber, Layer, Scope, Stream } from "effect"
  3. import * as TestClock from "effect/testing/TestClock"
  4. import { Integration } from "@opencode-ai/core/integration"
  5. import { Credential } from "@opencode-ai/core/credential"
  6. import { EventV2 } from "@opencode-ai/core/event"
  7. import { it } from "./lib/effect"
  8. const layer = Integration.locationLayer.pipe(
  9. Layer.provide(EventV2.defaultLayer),
  10. Layer.provide(
  11. Layer.mock(Credential.Service)({
  12. create: () => Effect.die("unexpected credential creation"),
  13. list: () => Effect.succeed([]),
  14. }),
  15. ),
  16. )
  17. function connectionLayer(
  18. created: Array<{
  19. integrationID: Integration.ID
  20. label?: string
  21. value: Credential.Info
  22. }>,
  23. ) {
  24. return Integration.locationLayer.pipe(
  25. Layer.provideMerge(EventV2.defaultLayer),
  26. Layer.provide(
  27. Layer.mock(Credential.Service)({
  28. create: (input) =>
  29. Effect.sync(() => {
  30. created.push(input)
  31. return new Credential.Stored({
  32. id: Credential.ID.create(),
  33. integrationID: input.integrationID,
  34. label: input.label ?? "default",
  35. value: input.value,
  36. })
  37. }),
  38. list: () => Effect.succeed([]),
  39. }),
  40. ),
  41. )
  42. }
  43. describe("Integration", () => {
  44. it.effect("registers integrations through the editor", () =>
  45. Effect.gen(function* () {
  46. const integrations = yield* Integration.Service
  47. const scope = yield* Scope.fork(yield* Scope.Scope)
  48. const openai = Integration.ID.make("openai")
  49. yield* integrations
  50. .update((editor) => editor.update(openai, (integration) => (integration.name = "OpenAI")))
  51. .pipe(Scope.provide(scope))
  52. expect(yield* integrations.get(openai)).toEqual(
  53. new Integration.Info({ id: openai, name: "OpenAI", methods: [], connections: [] }),
  54. )
  55. yield* Scope.close(scope, Exit.void)
  56. expect(yield* integrations.get(openai)).toBeUndefined()
  57. }).pipe(Effect.provide(layer)),
  58. )
  59. it.effect("reveals the previous registration when an override closes", () =>
  60. Effect.gen(function* () {
  61. const integrations = yield* Integration.Service
  62. const id = Integration.ID.make("openai")
  63. const first = yield* Scope.fork(yield* Scope.Scope)
  64. const second = yield* Scope.fork(yield* Scope.Scope)
  65. yield* integrations
  66. .update((editor) => editor.update(id, (integration) => (integration.name = "OpenAI")))
  67. .pipe(Scope.provide(first))
  68. yield* integrations
  69. .update((editor) => editor.update(id, (integration) => (integration.name = "OpenAI Override")))
  70. .pipe(Scope.provide(second))
  71. expect((yield* integrations.get(id))?.name).toBe("OpenAI Override")
  72. yield* Scope.close(second, Exit.void)
  73. expect((yield* integrations.get(id))?.name).toBe("OpenAI")
  74. expect((yield* integrations.list()).map((integration) => integration.id)).toEqual([id])
  75. }).pipe(Effect.provide(layer)),
  76. )
  77. it.effect("registers and overrides methods independently", () =>
  78. Effect.gen(function* () {
  79. const integrations = yield* Integration.Service
  80. const integrationID = Integration.ID.make("openai")
  81. const methodID = Integration.MethodID.make("chatgpt")
  82. const first = yield* Scope.fork(yield* Scope.Scope)
  83. const second = yield* Scope.fork(yield* Scope.Scope)
  84. const authorize = () =>
  85. Effect.succeed({
  86. mode: "auto" as const,
  87. url: "https://example.com/authorize",
  88. instructions: "Sign in",
  89. callback: Effect.never,
  90. })
  91. yield* integrations
  92. .update((editor) =>
  93. editor.method.update({
  94. integrationID,
  95. method: { id: methodID, type: "oauth", label: "ChatGPT" },
  96. authorize,
  97. }),
  98. )
  99. .pipe(Scope.provide(first))
  100. yield* integrations
  101. .update((editor) => {
  102. expect(editor.get(integrationID)).toEqual({ id: integrationID, name: "openai" })
  103. expect(editor.list()).toEqual([{ id: integrationID, name: "openai" }])
  104. expect(editor.method.list(integrationID)).toEqual([
  105. expect.objectContaining({ id: methodID, label: "ChatGPT" }),
  106. ])
  107. editor.method.update({
  108. integrationID,
  109. method: { id: methodID, type: "oauth", label: "ChatGPT Override" },
  110. authorize,
  111. })
  112. })
  113. .pipe(Scope.provide(second))
  114. expect((yield* integrations.get(integrationID))?.name).toBe("openai")
  115. expect((yield* integrations.get(integrationID))?.methods[0]).toMatchObject({ label: "ChatGPT Override" })
  116. yield* Scope.close(second, Exit.void)
  117. expect((yield* integrations.get(integrationID))?.methods[0]).toMatchObject({ label: "ChatGPT" })
  118. expect((yield* integrations.get(integrationID))?.methods).toEqual([expect.objectContaining({ id: methodID })])
  119. }).pipe(Effect.provide(layer)),
  120. )
  121. it.effect("connects with a key and stores the credential", () => {
  122. const created: Array<{
  123. integrationID: Integration.ID
  124. label?: string
  125. value: Credential.Info
  126. }> = []
  127. return Effect.gen(function* () {
  128. const integrations = yield* Integration.Service
  129. const events = yield* EventV2.Service
  130. const integrationID = Integration.ID.make("openai")
  131. yield* integrations.update((editor) =>
  132. editor.method.update({
  133. integrationID,
  134. method: { type: "key", label: "API key" },
  135. }),
  136. )
  137. const updated = yield* events.subscribe(Integration.Event.Updated).pipe(
  138. Stream.take(1),
  139. Stream.runCollect,
  140. Effect.forkScoped,
  141. )
  142. yield* Effect.yieldNow
  143. yield* integrations.connection.key({
  144. integrationID,
  145. key: "secret",
  146. label: "Work",
  147. })
  148. expect(created).toEqual([
  149. {
  150. integrationID,
  151. label: "Work",
  152. value: new Credential.Key({ type: "key", key: "secret" }),
  153. },
  154. ])
  155. expect((yield* Fiber.join(updated)).length).toBe(1)
  156. }).pipe(Effect.provide(connectionLayer(created)))
  157. })
  158. it.effect("completes code OAuth once and stores the credential", () => {
  159. const created: Array<{
  160. integrationID: Integration.ID
  161. label?: string
  162. value: Credential.Info
  163. }> = []
  164. return Effect.gen(function* () {
  165. const integrations = yield* Integration.Service
  166. const integrationID = Integration.ID.make("openai")
  167. const methodID = Integration.MethodID.make("chatgpt")
  168. yield* integrations.update((editor) =>
  169. editor.method.update({
  170. integrationID,
  171. method: { id: methodID, type: "oauth", label: "ChatGPT" },
  172. authorize: () =>
  173. Effect.succeed({
  174. mode: "code" as const,
  175. url: "https://example.com/authorize",
  176. instructions: "Paste the code",
  177. callback: (code: string) =>
  178. Effect.succeed(
  179. new Credential.OAuth({
  180. type: "oauth",
  181. methodID,
  182. access: "access",
  183. refresh: "refresh",
  184. expires: 1,
  185. metadata: { code },
  186. }),
  187. ),
  188. }),
  189. }),
  190. )
  191. const attempt = yield* integrations.connection.oauth({
  192. integrationID,
  193. methodID,
  194. inputs: {},
  195. label: "Personal",
  196. })
  197. expect(attempt.mode).toBe("code")
  198. yield* integrations.attempt.complete({ attemptID: attempt.attemptID, code: "1234" })
  199. expect(created[0]).toEqual({
  200. integrationID,
  201. label: "Personal",
  202. value: new Credential.OAuth({
  203. type: "oauth",
  204. methodID,
  205. access: "access",
  206. refresh: "refresh",
  207. expires: 1,
  208. metadata: { code: "1234" },
  209. }),
  210. })
  211. }).pipe(Effect.provide(connectionLayer(created)))
  212. })
  213. it.effect("keeps code attempts open when the code is missing and closes them on cancel", () => {
  214. const created: Array<{
  215. integrationID: Integration.ID
  216. label?: string
  217. value: Credential.Info
  218. }> = []
  219. return Effect.gen(function* () {
  220. const integrations = yield* Integration.Service
  221. const integrationID = Integration.ID.make("openai")
  222. const methodID = Integration.MethodID.make("chatgpt")
  223. let closed = false
  224. yield* integrations.update((editor) =>
  225. editor.method.update({
  226. integrationID,
  227. method: { id: methodID, type: "oauth", label: "ChatGPT" },
  228. authorize: () =>
  229. Effect.addFinalizer(() => Effect.sync(() => (closed = true))).pipe(
  230. Effect.as({
  231. mode: "code" as const,
  232. url: "https://example.com/authorize",
  233. instructions: "Paste the code",
  234. callback: () => Effect.die("unexpected callback"),
  235. }),
  236. ),
  237. }),
  238. )
  239. const attempt = yield* integrations.connection.oauth({ integrationID, methodID, inputs: {} })
  240. expect(yield* integrations.attempt.complete({ attemptID: attempt.attemptID }).pipe(Effect.flip)).toBeInstanceOf(
  241. Integration.CodeRequiredError,
  242. )
  243. expect(closed).toBe(false)
  244. yield* integrations.attempt.cancel(attempt.attemptID)
  245. expect(closed).toBe(true)
  246. expect(created).toEqual([])
  247. }).pipe(Effect.provide(connectionLayer(created)))
  248. })
  249. it.effect("completes auto OAuth in the background", () => {
  250. const created: Array<{
  251. integrationID: Integration.ID
  252. label?: string
  253. value: Credential.Info
  254. }> = []
  255. return Effect.gen(function* () {
  256. const integrations = yield* Integration.Service
  257. const integrationID = Integration.ID.make("openai")
  258. const methodID = Integration.MethodID.make("browser")
  259. yield* integrations.update((editor) =>
  260. editor.method.update({
  261. integrationID,
  262. method: { id: methodID, type: "oauth", label: "Browser" },
  263. authorize: () =>
  264. Effect.succeed({
  265. mode: "auto" as const,
  266. url: "https://example.com/authorize",
  267. instructions: "Sign in",
  268. callback: Effect.succeed(
  269. new Credential.OAuth({ type: "oauth", methodID, access: "access", refresh: "refresh", expires: 1 }),
  270. ),
  271. }),
  272. }),
  273. )
  274. const attempt = yield* integrations.connection.oauth({ integrationID, methodID, inputs: {} })
  275. yield* Effect.yieldNow
  276. expect(yield* integrations.attempt.status(attempt.attemptID)).toEqual({
  277. status: "complete",
  278. time: attempt.time,
  279. })
  280. expect(created).toHaveLength(1)
  281. }).pipe(Effect.provide(connectionLayer(created)))
  282. })
  283. it.effect("expires abandoned OAuth attempts", () => {
  284. const created: Array<{
  285. integrationID: Integration.ID
  286. label?: string
  287. value: Credential.Info
  288. }> = []
  289. return Effect.gen(function* () {
  290. const integrations = yield* Integration.Service
  291. const integrationID = Integration.ID.make("openai")
  292. const methodID = Integration.MethodID.make("browser")
  293. let closed = false
  294. yield* integrations.update((editor) =>
  295. editor.method.update({
  296. integrationID,
  297. method: { id: methodID, type: "oauth", label: "Browser" },
  298. authorize: () =>
  299. Effect.addFinalizer(() => Effect.sync(() => (closed = true))).pipe(
  300. Effect.as({
  301. mode: "auto" as const,
  302. url: "https://example.com/authorize",
  303. instructions: "Sign in",
  304. callback: Effect.never,
  305. }),
  306. ),
  307. }),
  308. )
  309. const attempt = yield* integrations.connection.oauth({ integrationID, methodID, inputs: {} })
  310. expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10)))
  311. yield* TestClock.adjust(Duration.minutes(10))
  312. yield* Effect.yieldNow
  313. expect(yield* integrations.attempt.status(attempt.attemptID)).toEqual({
  314. status: "expired",
  315. time: attempt.time,
  316. })
  317. expect(closed).toBe(true)
  318. expect(created).toEqual([])
  319. }).pipe(Effect.provide(connectionLayer(created)))
  320. })
  321. it.effect("projects credential and env connections", () => {
  322. const integrationID = Integration.ID.make("acme")
  323. const rows = [
  324. {
  325. id: Credential.ID.create(),
  326. integrationID,
  327. label: "Work",
  328. value: new Credential.Key({ type: "key", key: "a" }),
  329. },
  330. {
  331. id: Credential.ID.create(),
  332. integrationID,
  333. label: "Personal",
  334. value: new Credential.Key({ type: "key", key: "b" }),
  335. },
  336. ]
  337. const projectionLayer = Integration.locationLayer.pipe(
  338. Layer.provide(EventV2.defaultLayer),
  339. Layer.provide(
  340. Layer.mock(Credential.Service)({
  341. list: () => Effect.succeed(rows.map((row) => new Credential.Stored(row))),
  342. }),
  343. ),
  344. )
  345. return Effect.acquireUseRelease(
  346. Effect.sync(() => {
  347. const previous = process.env.INTEGRATION_TEST_ACME_KEY
  348. process.env.INTEGRATION_TEST_ACME_KEY = "secret"
  349. delete process.env.INTEGRATION_TEST_ACME_MISSING
  350. return previous
  351. }),
  352. () =>
  353. Effect.gen(function* () {
  354. const integrations = yield* Integration.Service
  355. yield* integrations.update((editor) =>
  356. editor.method.update({
  357. integrationID,
  358. method: {
  359. type: "env",
  360. names: ["INTEGRATION_TEST_ACME_KEY", "INTEGRATION_TEST_ACME_MISSING"],
  361. },
  362. }),
  363. )
  364. // Stored credentials and detected env vars appear as connections.
  365. expect((yield* integrations.get(integrationID))?.connections).toEqual([
  366. { type: "credential", id: rows[0]!.id, label: "Work" },
  367. {
  368. type: "credential",
  369. id: rows[1]!.id,
  370. label: "Personal",
  371. },
  372. { type: "env", name: "INTEGRATION_TEST_ACME_KEY" },
  373. ])
  374. expect(yield* integrations.connection.forIntegration(integrationID)).toEqual({
  375. type: "credential",
  376. id: rows[1]!.id,
  377. label: "Personal",
  378. })
  379. }).pipe(Effect.provide(projectionLayer)),
  380. (previous) =>
  381. Effect.sync(() => {
  382. if (previous === undefined) delete process.env.INTEGRATION_TEST_ACME_KEY
  383. else process.env.INTEGRATION_TEST_ACME_KEY = previous
  384. }),
  385. )
  386. })
  387. })