location-layer.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { DateTime, Deferred, Effect, Equal, Hash, Layer, Schema, Stream } from "effect"
  5. import { Tool } from "@opencode-ai/core/public"
  6. import { define } from "@opencode-ai/plugin/v2/effect"
  7. import { AgentV2 } from "@opencode-ai/core/agent"
  8. import { Catalog } from "@opencode-ai/core/catalog"
  9. import { LocationServiceMap } from "@opencode-ai/core/location-layer"
  10. import { Location } from "@opencode-ai/core/location"
  11. import { ModelV2 } from "@opencode-ai/core/model"
  12. import { PluginBoot } from "@opencode-ai/core/plugin/boot"
  13. import { ProjectV2 } from "@opencode-ai/core/project"
  14. import { ProviderV2 } from "@opencode-ai/core/provider"
  15. import { AbsolutePath } from "@opencode-ai/core/schema"
  16. import { SessionV2 } from "@opencode-ai/core/session"
  17. import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
  18. import { tmpdir } from "./fixture/tmpdir"
  19. import { testEffect } from "./lib/effect"
  20. import { toolDefinitions } from "./lib/tool"
  21. import { FSUtil } from "../src/fs-util"
  22. import { Credential } from "../src/credential"
  23. import { Database } from "../src/database/database"
  24. import { EventV2 } from "../src/event"
  25. import { Global } from "../src/global"
  26. import { ModelsDev } from "../src/models-dev"
  27. import { Npm } from "../src/npm"
  28. import { Project } from "../src/project"
  29. import { Reference } from "../src/reference"
  30. import { ToolRegistry } from "../src/tool/registry"
  31. import { ApplicationTools } from "../src/tool/application-tools"
  32. const applicationTools = ApplicationTools.layer
  33. const it = testEffect(
  34. Layer.merge(
  35. Layer.mergeAll(applicationTools, Database.defaultLayer, EventV2.defaultLayer),
  36. LocationServiceMap.layer.pipe(
  37. Layer.provide(applicationTools),
  38. Layer.provide(
  39. Layer.mergeAll(
  40. Project.defaultLayer,
  41. EventV2.defaultLayer,
  42. Credential.defaultLayer.pipe(Layer.fresh),
  43. Npm.defaultLayer,
  44. ModelsDev.defaultLayer,
  45. FSUtil.defaultLayer,
  46. Global.defaultLayer,
  47. ),
  48. ),
  49. ),
  50. ),
  51. )
  52. describe("LocationServiceMap", () => {
  53. it.effect("compares equivalent location refs by value", () =>
  54. Effect.sync(() => {
  55. const directory = AbsolutePath.make("/project")
  56. expect(Equal.equals(Location.Ref.make({ directory }), Location.Ref.make({ directory }))).toBe(true)
  57. expect(Hash.hash(Location.Ref.make({ directory }))).toBe(
  58. Hash.hash(Location.Ref.make({ directory, workspaceID: undefined })),
  59. )
  60. }),
  61. )
  62. it.live("isolates location state while sharing location policy with catalog", () =>
  63. Effect.acquireRelease(
  64. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  65. (dirs) => Effect.promise(() => Promise.all(dirs.map((dir) => dir[Symbol.asyncDispose]())).then(() => undefined)),
  66. ).pipe(
  67. Effect.flatMap(([blocked, allowed]) =>
  68. Effect.gen(function* () {
  69. yield* (yield* ApplicationTools.Service).register({
  70. application_context: Tool.make({
  71. description: "Read application context",
  72. input: Schema.Struct({}),
  73. output: Schema.Struct({ ok: Schema.Boolean }),
  74. execute: () => Effect.succeed({ ok: true }),
  75. }),
  76. })
  77. yield* Effect.promise(() =>
  78. fs.writeFile(
  79. path.join(blocked.path, "opencode.json"),
  80. JSON.stringify({
  81. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "test" }] },
  82. }),
  83. ),
  84. )
  85. const update = (directory: string) =>
  86. Effect.gen(function* () {
  87. yield* PluginBoot.Service.use((boot) => boot.wait())
  88. yield* Reference.Service
  89. const catalog = yield* Catalog.Service
  90. yield* catalog.transform((editor) => editor.provider.update(ProviderV2.ID.make("test"), () => {}))
  91. return {
  92. providers: yield* catalog.provider.all(),
  93. tools: yield* toolDefinitions(yield* ToolRegistry.Service),
  94. }
  95. }).pipe(
  96. Effect.scoped,
  97. Effect.provide(LocationServiceMap.get(Location.Ref.make({ directory: AbsolutePath.make(directory) }))),
  98. )
  99. const blockedState = yield* update(blocked.path)
  100. expect(blockedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(false)
  101. expect(blockedState.tools.map((tool) => tool.name).sort()).toEqual([
  102. "application_context",
  103. "apply_patch",
  104. "bash",
  105. "edit",
  106. "glob",
  107. "grep",
  108. "question",
  109. "read",
  110. "skill",
  111. "todowrite",
  112. "webfetch",
  113. "websearch",
  114. "write",
  115. ])
  116. const allowedState = yield* update(allowed.path)
  117. expect(allowedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(true)
  118. expect(allowedState.tools.map((tool) => tool.name).sort()).toEqual([
  119. "application_context",
  120. "apply_patch",
  121. "bash",
  122. "edit",
  123. "glob",
  124. "grep",
  125. "question",
  126. "read",
  127. "skill",
  128. "todowrite",
  129. "webfetch",
  130. "websearch",
  131. "write",
  132. ])
  133. }),
  134. ),
  135. ),
  136. )
  137. it.live("rejects an unavailable selected model during location model resolution", () =>
  138. Effect.acquireRelease(
  139. Effect.promise(() => tmpdir()),
  140. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  141. ).pipe(
  142. Effect.flatMap((dir) =>
  143. Effect.gen(function* () {
  144. const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
  145. yield* Effect.promise(() =>
  146. fs.writeFile(
  147. path.join(dir.path, "opencode.json"),
  148. JSON.stringify({
  149. providers: {
  150. unavailable: {
  151. name: "Unavailable",
  152. api: { type: "native", settings: {} },
  153. models: { chat: { disabled: true } },
  154. },
  155. },
  156. }),
  157. ),
  158. )
  159. const failure = yield* SessionRunnerModel.Service.use((models) =>
  160. models.resolve(
  161. SessionV2.Info.make({
  162. id: SessionV2.ID.make("ses_unavailable_model"),
  163. projectID: ProjectV2.ID.global,
  164. title: "test",
  165. model: {
  166. id: ModelV2.ID.make("chat"),
  167. providerID: ProviderV2.ID.make("unavailable"),
  168. },
  169. cost: 0,
  170. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  171. time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
  172. location,
  173. }),
  174. ),
  175. ).pipe(Effect.provide(LocationServiceMap.get(location)), Effect.flip)
  176. expect(failure).toMatchObject({
  177. _tag: "SessionRunnerModel.ModelUnavailableError",
  178. providerID: "unavailable",
  179. modelID: "chat",
  180. })
  181. }),
  182. ),
  183. ),
  184. )
  185. it.live("installs public plugins into a location", () =>
  186. Effect.acquireRelease(
  187. Effect.promise(() => tmpdir()),
  188. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  189. ).pipe(
  190. Effect.flatMap((dir) =>
  191. Effect.gen(function* () {
  192. const boot = yield* PluginBoot.Service
  193. const catalogUpdated = yield* Deferred.make<void>()
  194. const seen: string[] = []
  195. yield* boot.add(
  196. define({
  197. id: "reviewer",
  198. effect: (ctx) =>
  199. Effect.gen(function* () {
  200. yield* ctx.event.subscribe("catalog.updated").pipe(
  201. Stream.runForEach(() => Deferred.succeed(catalogUpdated, undefined).pipe(Effect.asVoid)),
  202. Effect.forkScoped({ startImmediately: true }),
  203. )
  204. yield* ctx.agent.transform((agent) => {
  205. agent.update("reviewer", (item) => {
  206. item.description = "Reviews code"
  207. item.mode = "subagent"
  208. })
  209. })
  210. seen.push((yield* ctx.agent.get("reviewer"))?.description ?? "")
  211. yield* ctx.catalog.transform((catalog) => {
  212. catalog.provider.update("public", (provider) => {
  213. provider.name = "Public provider"
  214. })
  215. })
  216. }),
  217. }),
  218. )
  219. yield* Deferred.await(catalogUpdated)
  220. expect(seen).toEqual(["Reviews code"])
  221. expect(yield* (yield* AgentV2.Service).get(AgentV2.ID.make("reviewer"))).toMatchObject({
  222. description: "Reviews code",
  223. mode: "subagent",
  224. })
  225. }).pipe(
  226. Effect.scoped,
  227. Effect.provide(LocationServiceMap.get(Location.Ref.make({ directory: AbsolutePath.make(dir.path) }))),
  228. ),
  229. ),
  230. ),
  231. )
  232. })