location-layer.test.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { DateTime, Effect, Equal, Hash, Layer, Schema } from "effect"
  5. import { Tool } from "@opencode-ai/core/tool/tool"
  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 { PluginV2 } from "@opencode-ai/core/plugin"
  12. import { ModelV2 } from "@opencode-ai/core/model"
  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.live("reuses cached services for constructed and decoded location refs", () =>
  54. Effect.acquireRelease(
  55. Effect.promise(() => tmpdir()),
  56. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  57. ).pipe(
  58. Effect.flatMap((dir) =>
  59. Effect.scoped(
  60. Effect.gen(function* () {
  61. const locations = yield* LocationServiceMap
  62. const directory = AbsolutePath.make(dir.path)
  63. const constructed = Location.Ref.make({ directory })
  64. const decoded = Schema.decodeUnknownSync(Location.Ref)({ directory })
  65. expect(constructed).toEqual({ directory, workspaceID: undefined })
  66. expect(decoded).toEqual(constructed)
  67. expect(Equal.equals(constructed, decoded)).toBe(true)
  68. expect(Hash.hash(constructed)).toBe(Hash.hash(decoded))
  69. expect(yield* locations.contextEffect(constructed)).toBe(yield* locations.contextEffect(decoded))
  70. }),
  71. ),
  72. ),
  73. ),
  74. )
  75. it.live("isolates location state while sharing location policy with catalog", () =>
  76. Effect.acquireRelease(
  77. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  78. (dirs) => Effect.promise(() => Promise.all(dirs.map((dir) => dir[Symbol.asyncDispose]())).then(() => undefined)),
  79. ).pipe(
  80. Effect.flatMap(([blocked, allowed]) =>
  81. Effect.gen(function* () {
  82. yield* (yield* ApplicationTools.Service).register({
  83. application_context: Tool.make({
  84. description: "Read application context",
  85. input: Schema.Struct({}),
  86. output: Schema.Struct({ ok: Schema.Boolean }),
  87. execute: () => Effect.succeed({ ok: true }),
  88. }),
  89. })
  90. yield* Effect.promise(() =>
  91. fs.writeFile(
  92. path.join(blocked.path, "opencode.json"),
  93. JSON.stringify({
  94. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "test" }] },
  95. }),
  96. ),
  97. )
  98. const update = (directory: string) =>
  99. Effect.gen(function* () {
  100. yield* Reference.Service
  101. const catalog = yield* Catalog.Service
  102. yield* catalog.transform((editor) => editor.provider.update(ProviderV2.ID.make("test"), () => {}))
  103. return {
  104. providers: yield* catalog.provider.all(),
  105. tools: yield* toolDefinitions(yield* ToolRegistry.Service),
  106. }
  107. }).pipe(
  108. Effect.scoped,
  109. Effect.provide(LocationServiceMap.get(Location.Ref.make({ directory: AbsolutePath.make(directory) }))),
  110. )
  111. const blockedState = yield* update(blocked.path)
  112. expect(blockedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(false)
  113. expect(blockedState.tools.map((tool) => tool.name).sort()).toEqual([
  114. "application_context",
  115. "apply_patch",
  116. "bash",
  117. "edit",
  118. "glob",
  119. "grep",
  120. "question",
  121. "read",
  122. "skill",
  123. "todowrite",
  124. "webfetch",
  125. "websearch",
  126. "write",
  127. ])
  128. const allowedState = yield* update(allowed.path)
  129. expect(allowedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(true)
  130. expect(allowedState.tools.map((tool) => tool.name).sort()).toEqual([
  131. "application_context",
  132. "apply_patch",
  133. "bash",
  134. "edit",
  135. "glob",
  136. "grep",
  137. "question",
  138. "read",
  139. "skill",
  140. "todowrite",
  141. "webfetch",
  142. "websearch",
  143. "write",
  144. ])
  145. }),
  146. ),
  147. ),
  148. )
  149. it.live("rejects an unavailable selected model during location model resolution", () =>
  150. Effect.acquireRelease(
  151. Effect.promise(() => tmpdir()),
  152. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  153. ).pipe(
  154. Effect.flatMap((dir) =>
  155. Effect.gen(function* () {
  156. const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
  157. yield* Effect.promise(() =>
  158. fs.writeFile(
  159. path.join(dir.path, "opencode.json"),
  160. JSON.stringify({
  161. providers: {
  162. unavailable: {
  163. name: "Unavailable",
  164. api: { type: "native", settings: {} },
  165. models: { chat: { disabled: true } },
  166. },
  167. },
  168. }),
  169. ),
  170. )
  171. const failure = yield* SessionRunnerModel.Service.use((models) =>
  172. models.resolve(
  173. SessionV2.Info.make({
  174. id: SessionV2.ID.make("ses_unavailable_model"),
  175. projectID: ProjectV2.ID.global,
  176. title: "test",
  177. model: {
  178. id: ModelV2.ID.make("chat"),
  179. providerID: ProviderV2.ID.make("unavailable"),
  180. },
  181. cost: 0,
  182. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  183. time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
  184. location,
  185. }),
  186. ),
  187. ).pipe(Effect.provide(LocationServiceMap.get(location)), Effect.flip)
  188. expect(failure).toMatchObject({
  189. _tag: "SessionRunnerModel.ModelUnavailableError",
  190. providerID: "unavailable",
  191. modelID: "chat",
  192. })
  193. }),
  194. ),
  195. ),
  196. )
  197. it.live("installs public plugins into a location", () =>
  198. Effect.acquireRelease(
  199. Effect.promise(() => tmpdir()),
  200. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  201. ).pipe(
  202. Effect.flatMap((dir) =>
  203. Effect.gen(function* () {
  204. const plugins = yield* PluginV2.Service
  205. const reviewer = define({
  206. id: "reviewer",
  207. effect: (ctx) =>
  208. ctx.agent
  209. .transform((agent) => {
  210. agent.update("reviewer", (item) => {
  211. item.description = "Reviews code"
  212. item.mode = "subagent"
  213. })
  214. })
  215. .pipe(Effect.asVoid),
  216. })
  217. yield* plugins.add(PluginV2.ID.make(reviewer.id), reviewer.effect)
  218. expect(yield* (yield* AgentV2.Service).get(AgentV2.ID.make("reviewer"))).toMatchObject({
  219. description: "Reviews code",
  220. mode: "subagent",
  221. })
  222. }).pipe(
  223. Effect.scoped,
  224. Effect.provide(LocationServiceMap.get(Location.Ref.make({ directory: AbsolutePath.make(dir.path) }))),
  225. ),
  226. ),
  227. ),
  228. )
  229. })