location-layer.test.ts 8.6 KB

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