test(core): share env and polling helpers, fix an env leak (#61166)

This commit is contained in:
Aiden Cline
2026-11-01 21:17:41 -06:00
committed by GitHub
Unverified
parent 00e97c71d9
commit ae7d32906b
21 changed files with 172 additions and 423 deletions
-1
View File
@@ -11,7 +11,6 @@
"test/loop.test.ts",
"test/promise.test.ts",
"test/testing.test.ts",
"test/testing-media.test.ts",
"test/provider/checkpoint.test.ts"
]
}
+16 -27
View File
@@ -13,6 +13,7 @@ import { ModelResolver } from "@opencode/core/model-resolver"
import { Provider } from "@opencode/core/provider"
import { AbsolutePath } from "@opencode/core/schema"
import { Money } from "@opencode/schema/money"
import { withEnv } from "./fixture/env"
import { location } from "./fixture/location"
import { testEffect } from "./lib/effect"
@@ -202,8 +203,7 @@ describe("Provider and Model", () => {
yield* settle(
Ref.get(log).pipe(
Effect.map(
(types) =>
types.lastIndexOf(Model.Event.Updated.type) > types.lastIndexOf(Credential.Event.Updated.type),
(types) => types.lastIndexOf(Model.Event.Updated.type) > types.lastIndexOf(Credential.Event.Updated.type),
),
),
)
@@ -360,32 +360,21 @@ describe("Provider and Model", () => {
})
it.effect("projects environment connections without a catalog plugin", () =>
Effect.acquireUseRelease(
Effect.sync(() => {
const previous = process.env.CATALOG_TEST_API_KEY
process.env.CATALOG_TEST_API_KEY = "secret"
return previous
}),
() =>
Effect.gen(function* () {
const providers = yield* Provider.Service
const integrations = yield* Integration.Service
const providerID = Provider.ID.make("test")
yield* integrations.transform((editor) =>
editor.method.update({
integrationID: Integration.ID.make(providerID),
method: { type: "env", names: ["CATALOG_TEST_API_KEY"] },
}),
)
yield* providers.transform((editor) => editor.update(providerID, () => {}))
withEnv({ CATALOG_TEST_API_KEY: "secret" }, () =>
Effect.gen(function* () {
const providers = yield* Provider.Service
const integrations = yield* Integration.Service
const providerID = Provider.ID.make("test")
yield* integrations.transform((editor) =>
editor.method.update({
integrationID: Integration.ID.make(providerID),
method: { type: "env", names: ["CATALOG_TEST_API_KEY"] },
}),
)
yield* providers.transform((editor) => editor.update(providerID, () => {}))
expect((yield* providers.available()).map((provider) => provider.id)).toContain(providerID)
}),
(previous) =>
Effect.sync(() => {
if (previous === undefined) delete process.env.CATALOG_TEST_API_KEY
else process.env.CATALOG_TEST_API_KEY = previous
}),
expect((yield* providers.available()).map((provider) => provider.id)).toContain(providerID)
}),
),
)
+7 -21
View File
@@ -30,6 +30,7 @@ import { ManagedPolicy } from "@opencode/core/managed-policy"
import { Wildcard } from "@opencode/core/util/wildcard"
import { Integration } from "@opencode/schema/integration"
import { emptyCredentialNode, emptyWellknownNode } from "../fixture/config-nodes"
import { withEnv } from "../fixture/env"
import { location } from "../fixture/location"
import { tmpdir } from "../fixture/tmpdir"
import { testEffect } from "../lib/effect"
@@ -1613,18 +1614,12 @@ describe("Config", () => {
)
it.live("substitutes environment variables and relative file contents", () =>
Effect.acquireUseRelease(
Effect.sync(() => {
const previous = {
token: process.env.OPENCODE_TEST_MCP_TOKEN,
missing: process.env.OPENCODE_TEST_MISSING,
flag: process.env.OPENCODE_TEST_FLAG,
}
process.env.OPENCODE_TEST_FLAG = "false"
process.env.OPENCODE_TEST_MCP_TOKEN = String.raw`C:\Users\new\"secret"`
delete process.env.OPENCODE_TEST_MISSING
return previous
}),
withEnv(
{
OPENCODE_TEST_FLAG: "false",
OPENCODE_TEST_MCP_TOKEN: String.raw`C:\Users\new\"secret"`,
OPENCODE_TEST_MISSING: undefined,
},
() =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
@@ -1676,15 +1671,6 @@ describe("Config", () => {
}),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
),
(previous) =>
Effect.sync(() => {
if (previous.token === undefined) delete process.env.OPENCODE_TEST_MCP_TOKEN
else process.env.OPENCODE_TEST_MCP_TOKEN = previous.token
if (previous.missing === undefined) delete process.env.OPENCODE_TEST_MISSING
else process.env.OPENCODE_TEST_MISSING = previous.missing
if (previous.flag === undefined) delete process.env.OPENCODE_TEST_FLAG
else process.env.OPENCODE_TEST_FLAG = previous.flag
}),
),
)
+1 -8
View File
@@ -8,6 +8,7 @@ import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { Document, Event, Info, type Entry } from "@opencode/schema/config"
import { Effect, Layer, Schema, Stream } from "effect"
import { waitUntil } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "../plugin/fixture"
@@ -75,11 +76,3 @@ const limits = Effect.fnUntraced(function* (image: Image.Interface) {
if (error._tag !== "Image.SizeError") return yield* Effect.die(error)
return { maxWidth: error.maxWidth, maxHeight: error.maxHeight, maxBytes: error.maxBytes }
})
const waitUntil = Effect.fnUntraced(function* (condition: Effect.Effect<boolean>) {
for (let attempt = 0; attempt < 200; attempt++) {
if (yield* condition) return
yield* Effect.sleep("10 millis")
}
yield* Effect.die(new Error("Timed out waiting for image config reload"))
})
+3 -19
View File
@@ -15,6 +15,7 @@ import { Credential } from "@opencode/core/credential"
import { ConfigIntegration } from "@opencode/core/config/integration"
import { WebSearch } from "@opencode/core/websearch"
import { Effect, Schema } from "effect"
import { waitUntil } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { organizationPolicy } from "../fixture/policy"
import { PluginTestLayer } from "../plugin/fixture"
@@ -309,13 +310,13 @@ describe("integration policy", () => {
// Only the required organization's connection works, and with it everything that organization supplies.
yield* credentials.create({ integrationID: Integration.ID.make("opencode"), value: consoleCredential(orgID) })
yield* eventually(available().pipe(Effect.map((ids) => ids.length > 0)))
yield* waitUntil(available().pipe(Effect.map((ids) => ids.length > 0)))
expect(yield* available()).toEqual(["acme-gateway", "opencode"])
expect(yield* searches()).toEqual(["opencode"])
// Switching back to the personal account revokes it again.
yield* credentials.activate(personal.id)
yield* eventually(available().pipe(Effect.map((ids) => ids.length === 0)))
yield* waitUntil(available().pipe(Effect.map((ids) => ids.length === 0)))
expect(yield* searches()).toEqual([])
}).pipe(Effect.provide(Config.testLayer([lockdown()]))),
)
@@ -400,20 +401,3 @@ describe("integration policy", () => {
}),
)
})
const eventually = Effect.fnUntraced(function* (condition: Effect.Effect<boolean>) {
const deadline = Date.now() + 10_000
while (Date.now() < deadline) {
if (yield* condition) return
yield* Effect.sleep("10 millis")
}
return yield* Effect.die("Timed out waiting for policy reload")
})
const waitUntil = Effect.fnUntraced(function* (condition: Effect.Effect<boolean>) {
for (let attempt = 0; attempt < 200; attempt++) {
if (yield* condition) return
yield* Effect.sleep("10 millis")
}
return yield* Effect.die("Timed out waiting for policy reload")
})
+1 -8
View File
@@ -36,6 +36,7 @@ import { AppProcess } from "@opencode/util/process"
import { Deferred, Effect, Layer, Schema } from "effect"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { AbsolutePath } from "@opencode/core/schema"
import { waitUntil } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "../plugin/fixture"
import { emptyCredentialNode, emptyWellknownNode } from "../fixture/config-nodes"
@@ -526,11 +527,3 @@ function referenceConfig(file: string, references: Record<string, string>) {
function title(value: string) {
return value.charAt(0).toUpperCase() + value.slice(1)
}
const waitUntil = Effect.fnUntraced(function* (condition: Effect.Effect<boolean>) {
for (let attempt = 0; attempt < 100; attempt++) {
if (yield* condition) return
yield* Effect.sleep("10 millis")
}
return yield* Effect.die("Timed out waiting for config plugin reloads")
})
+1 -8
View File
@@ -8,6 +8,7 @@ import { WebSearch } from "@opencode/core/websearch"
import { Document, Event, Info } from "@opencode/schema/config"
import { ConfigWebSearch } from "@opencode/schema/config/websearch"
import { Effect } from "effect"
import { waitUntil } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "../plugin/fixture"
@@ -42,11 +43,3 @@ describe("ConfigWebSearchPlugin.Plugin", () => {
function configured(websearch: ConfigWebSearch.Selection): Document {
return new Document({ type: "document", info: new Info({ websearch }) })
}
const waitUntil = Effect.fnUntraced(function* (condition: Effect.Effect<boolean>) {
for (let attempt = 0; attempt < 200; attempt++) {
if (yield* condition) return
yield* Effect.sleep("10 millis")
}
yield* Effect.die(new Error("Timed out waiting for websearch config reload"))
})
+96 -121
View File
@@ -9,7 +9,9 @@ import { LayerNode } from "@opencode/util/effect/layer-node"
import { Bus } from "@opencode/core/bus"
import { Integration } from "@opencode/core/integration"
import { State } from "@opencode/core/state"
import { withEnv } from "./fixture/env"
import { tmpdirScoped } from "./fixture/tmpdir"
import { eventually } from "./lib/eventually"
import { testEffect } from "./lib/effect"
const it = testEffect(AppNodeBuilder.build(LayerNode.group([Integration.node, Credential.node, Bus.node])))
@@ -34,21 +36,6 @@ const failingIt = testEffect(
AppNodeBuilder.build(LayerNode.group([Integration.node, Bus.node]), [Credential.node.replace(failingCredentialNode)]),
)
// Bounded by elapsed time rather than attempts, so a slow child process start on a busy machine still fits.
function eventually<A, E, R>(
effect: Effect.Effect<A, E, R>,
predicate: (value: A) => boolean,
deadline = Date.now() + 10_000,
): Effect.Effect<A, E | Error, R> {
return Effect.gen(function* () {
const value = yield* effect
if (predicate(value)) return value
if (Date.now() > deadline) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
return yield* eventually(effect, predicate, deadline)
})
}
describe("Integration", () => {
it.effect("registers integrations through the editor", () =>
Effect.gen(function* () {
@@ -566,124 +553,112 @@ describe("Integration", () => {
it.effect("projects credential and env connections", () => {
const integrationID = Integration.ID.make("acme")
return Effect.acquireUseRelease(
Effect.sync(() => {
const previous = process.env.INTEGRATION_TEST_ACME_KEY
process.env.INTEGRATION_TEST_ACME_KEY = "secret"
delete process.env.INTEGRATION_TEST_ACME_MISSING
return previous
}),
() =>
Effect.gen(function* () {
const integrations = yield* Integration.Service
const credentials = yield* Credential.Service
yield* integrations.transform((editor) =>
editor.method.update({
integrationID,
method: {
type: "env",
names: ["INTEGRATION_TEST_ACME_KEY", "INTEGRATION_TEST_ACME_MISSING"],
},
}),
)
const archived = yield* credentials.create({
return withEnv({ INTEGRATION_TEST_ACME_KEY: "secret", INTEGRATION_TEST_ACME_MISSING: undefined }, () =>
Effect.gen(function* () {
const integrations = yield* Integration.Service
const credentials = yield* Credential.Service
yield* integrations.transform((editor) =>
editor.method.update({
integrationID,
label: "Archived",
value: Credential.Key.make({ type: "key", key: "c" }),
})
const work = yield* credentials.create({
integrationID,
label: "Work",
value: Credential.Key.make({ type: "key", key: "a" }),
})
const personal = yield* credentials.create({
integrationID,
label: "Personal",
value: Credential.Key.make({ type: "key", key: "b" }),
})
method: {
type: "env",
names: ["INTEGRATION_TEST_ACME_KEY", "INTEGRATION_TEST_ACME_MISSING"],
},
}),
)
const archived = yield* credentials.create({
integrationID,
label: "Archived",
value: Credential.Key.make({ type: "key", key: "c" }),
})
const work = yield* credentials.create({
integrationID,
label: "Work",
value: Credential.Key.make({ type: "key", key: "a" }),
})
const personal = yield* credentials.create({
integrationID,
label: "Personal",
value: Credential.Key.make({ type: "key", key: "b" }),
})
// Stored credentials and detected env vars appear as connections.
expect((yield* integrations.get(integrationID))?.connections).toEqual([
{
type: "credential",
method: "key",
id: personal.id,
label: "Personal",
},
{
type: "credential",
method: "key",
id: work.id,
label: "Work",
},
{
type: "credential",
method: "key",
id: archived.id,
label: "Archived",
},
{ type: "env", name: "INTEGRATION_TEST_ACME_KEY" },
])
expect(yield* integrations.connection.active(integrationID)).toEqual({
// Stored credentials and detected env vars appear as connections.
expect((yield* integrations.get(integrationID))?.connections).toEqual([
{
type: "credential",
method: "key",
id: personal.id,
label: "Personal",
})
const bus = yield* Bus.Service
const events = new Array<{ type: string; data: unknown }>()
yield* bus.listen((event) => Effect.sync(() => events.push({ type: event.type, data: event.data })))
yield* integrations.connection.activate(work.id)
expect(yield* integrations.connection.active(integrationID)).toEqual({
},
{
type: "credential",
method: "key",
id: work.id,
label: "Work",
})
expect((yield* integrations.get(integrationID))?.connections.map((connection) => connection.type)).toEqual([
"credential",
"credential",
"credential",
"env",
])
expect(events).toEqual([
{ type: Credential.Event.Switched.type, data: { credentialID: work.id, integrationID } },
])
yield* integrations.connection.remove(archived.id)
expect(events).toEqual([
{ type: Credential.Event.Switched.type, data: { credentialID: work.id, integrationID } },
{ type: Credential.Event.Updated.type, data: {} },
])
yield* integrations.connection.remove(work.id)
expect(yield* integrations.connection.active(integrationID)).toEqual({
},
{
type: "credential",
method: "key",
id: personal.id,
label: "Personal",
})
yield* integrations.connection.remove(personal.id)
expect(yield* integrations.connection.active(integrationID)).toEqual({
type: "env",
name: "INTEGRATION_TEST_ACME_KEY",
})
expect(events).toEqual([
{ type: Credential.Event.Switched.type, data: { credentialID: work.id, integrationID } },
{ type: Credential.Event.Updated.type, data: {} },
{ type: Credential.Event.Updated.type, data: {} },
{ type: Credential.Event.Switched.type, data: { credentialID: personal.id, integrationID } },
{ type: Credential.Event.Updated.type, data: {} },
{ type: Credential.Event.Switched.type, data: { credentialID: null, integrationID } },
])
}),
(previous) =>
Effect.sync(() => {
if (previous === undefined) delete process.env.INTEGRATION_TEST_ACME_KEY
else process.env.INTEGRATION_TEST_ACME_KEY = previous
}),
id: archived.id,
label: "Archived",
},
{ type: "env", name: "INTEGRATION_TEST_ACME_KEY" },
])
expect(yield* integrations.connection.active(integrationID)).toEqual({
type: "credential",
method: "key",
id: personal.id,
label: "Personal",
})
const bus = yield* Bus.Service
const events = new Array<{ type: string; data: unknown }>()
yield* bus.listen((event) => Effect.sync(() => events.push({ type: event.type, data: event.data })))
yield* integrations.connection.activate(work.id)
expect(yield* integrations.connection.active(integrationID)).toEqual({
type: "credential",
method: "key",
id: work.id,
label: "Work",
})
expect((yield* integrations.get(integrationID))?.connections.map((connection) => connection.type)).toEqual([
"credential",
"credential",
"credential",
"env",
])
expect(events).toEqual([
{ type: Credential.Event.Switched.type, data: { credentialID: work.id, integrationID } },
])
yield* integrations.connection.remove(archived.id)
expect(events).toEqual([
{ type: Credential.Event.Switched.type, data: { credentialID: work.id, integrationID } },
{ type: Credential.Event.Updated.type, data: {} },
])
yield* integrations.connection.remove(work.id)
expect(yield* integrations.connection.active(integrationID)).toEqual({
type: "credential",
method: "key",
id: personal.id,
label: "Personal",
})
yield* integrations.connection.remove(personal.id)
expect(yield* integrations.connection.active(integrationID)).toEqual({
type: "env",
name: "INTEGRATION_TEST_ACME_KEY",
})
expect(events).toEqual([
{ type: Credential.Event.Switched.type, data: { credentialID: work.id, integrationID } },
{ type: Credential.Event.Updated.type, data: {} },
{ type: Credential.Event.Updated.type, data: {} },
{ type: Credential.Event.Switched.type, data: { credentialID: personal.id, integrationID } },
{ type: Credential.Event.Updated.type, data: {} },
{ type: Credential.Event.Switched.type, data: { credentialID: null, integrationID } },
])
}),
)
})
})
+20
View File
@@ -0,0 +1,20 @@
import { Effect } from "effect"
// Bounded by elapsed real time rather than attempts, so a busy machine still fits. Sleeps on a real timer, so it
// also works under TestClock.
export const eventually = <A, E, R>(
effect: Effect.Effect<A, E, R>,
predicate: (value: A) => boolean,
): Effect.Effect<A, E | Error, R> =>
Effect.gen(function* () {
const deadline = Date.now() + 10_000
while (true) {
const value = yield* effect
if (predicate(value)) return value
if (Date.now() > deadline) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
}
})
export const waitUntil = <E, R>(condition: Effect.Effect<boolean, E, R>) =>
eventually(condition, (ready) => ready).pipe(Effect.asVoid)
-17
View File
@@ -32,23 +32,6 @@ export function waitForTool(registry: Tool.Interface, name: string, remaining =
})
}
export function waitForCodeModeTool(
registry: Tool.Interface,
path: string,
remaining = 1000,
): Effect.Effect<Tool.Snapshot, Error> {
return Effect.gen(function* () {
const toolSet = yield* registry.snapshot()
if (toolSet.codeModeCatalog && codeModeListings(toolSet.codeModeCatalog).some((tool) => tool.path === path))
return toolSet
if (remaining === 0) {
return yield* Effect.fail(new Error(`Timed out waiting for Code Mode tool: ${path}`))
}
yield* Effect.promise(() => Bun.sleep(1))
return yield* waitForCodeModeTool(registry, path, remaining - 1)
})
}
/**
* Registers a core tool plugin's tools against the real registry without booting the
* full plugin host. Only the tool domain is live; focused tool tests exercise
+1 -21
View File
@@ -13,6 +13,7 @@ import { Variant } from "@opencode/core/variant"
import { ModelResolver } from "@opencode/core/model-resolver"
import { AISDK } from "@opencode/core/aisdk"
import { Npm } from "@opencode/util/npm"
import { withEnv } from "./fixture/env"
import { it } from "./lib/effect"
interface ModelOptions {
@@ -56,27 +57,6 @@ function model(packageName: string | undefined, options: ModelOptions = {}) {
return Info.make(info)
}
function withEnv<A, E, R>(variables: Record<string, string | undefined>, effect: () => Effect.Effect<A, E, R>) {
return Effect.acquireUseRelease(
Effect.sync(() => {
const previous = Object.fromEntries(Object.keys(variables).map((key) => [key, process.env[key]]))
Object.entries(variables).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
})
return previous
}),
effect,
(previous) =>
Effect.sync(() => {
Object.entries(previous).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
})
}),
)
}
function withConfigEnv<A, E, R>(env: Record<string, string>, effect: () => Effect.Effect<A, E, R>) {
return effect().pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))))
}
@@ -6,6 +6,7 @@ import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { AmazonBedrockPlugin } from "@opencode/core/plugin/provider/amazon-bedrock"
import { Provider } from "@opencode/core/provider"
import { withEnv } from "../fixture/env"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -22,27 +23,6 @@ function required<T>(value: T | undefined): T {
return value
}
function withEnv<A, E, R>(vars: Record<string, string | undefined>, fx: () => Effect.Effect<A, E, R>) {
return Effect.acquireUseRelease(
Effect.sync(() => {
const previous = Object.fromEntries(Object.keys(vars).map((key) => [key, process.env[key]]))
Object.entries(vars).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
})
return previous
}),
fx,
(previous) =>
Effect.sync(() => {
Object.entries(previous).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
})
}),
)
}
const noAmbientAWS = {
AWS_PROFILE: undefined,
AWS_ACCESS_KEY_ID: undefined,
@@ -6,6 +6,7 @@ import { PluginHost } from "@opencode/core/plugin/host"
import { CloudflareWorkersAIPlugin } from "@opencode/core/plugin/provider/cloudflare-workers-ai"
import { Provider } from "@opencode/core/provider"
import { Integration } from "@opencode/core/integration"
import { withEnv } from "../fixture/env"
import { drain } from "../lib/clock"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -24,27 +25,6 @@ function required<T>(value: T | undefined): T {
return value
}
function withEnv<A, E, R>(vars: Record<string, string | undefined>, effect: () => Effect.Effect<A, E, R>) {
return Effect.acquireUseRelease(
Effect.sync(() => {
const previous = Object.fromEntries(Object.keys(vars).map((key) => [key, process.env[key]]))
Object.entries(vars).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
})
return previous
}),
effect,
(previous) =>
Effect.sync(() =>
Object.entries(previous).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}),
),
)
}
const seed = Effect.fn(function* (fn: (provider: Provider.MutableInfo) => void) {
const catalog = yield* Provider.Service
yield* catalog.transform((catalog) => catalog.update(providerID, fn))
@@ -86,9 +66,7 @@ describe("CloudflareWorkersAIPlugin", () => {
type: "key",
label: "API key",
})
expect(required(yield* catalog.get(providerID)).package).toBe(
"@opencode/ai/providers/cloudflare-workers-ai",
)
expect(required(yield* catalog.get(providerID)).package).toBe("@opencode/ai/providers/cloudflare-workers-ai")
}),
),
)
@@ -4,31 +4,27 @@ import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { DatabricksPlugin } from "@opencode/core/plugin/provider/databricks"
import { Provider } from "@opencode/core/provider"
import { withEnv } from "../fixture/env"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
const it = testEffect(PluginTestLayer)
const providerID = Provider.ID.make("databricks")
const baseURLFor = Effect.fn(function* (host: string) {
const previous = process.env.DATABRICKS_HOST
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
if (previous === undefined) delete process.env.DATABRICKS_HOST
if (previous !== undefined) process.env.DATABRICKS_HOST = previous
const baseURLFor = (host: string) =>
withEnv({ DATABRICKS_HOST: host }, () =>
Effect.gen(function* () {
const catalog = yield* Provider.Service
yield* catalog.transform((catalog) => {
catalog.update(providerID, (item) => {
item.settings = { baseURL: "https://${DATABRICKS_HOST}/ai-gateway/mlflow/v1" }
})
})
const plugin = yield* Plugin.Service
yield* DatabricksPlugin.effect(yield* PluginHost.make(plugin, "test"))
return (yield* catalog.get(providerID))?.settings?.baseURL
}),
)
process.env.DATABRICKS_HOST = host
const catalog = yield* Provider.Service
yield* catalog.transform((catalog) => {
catalog.update(providerID, (item) => {
item.settings = { baseURL: "https://${DATABRICKS_HOST}/ai-gateway/mlflow/v1" }
})
})
const plugin = yield* Plugin.Service
yield* DatabricksPlugin.effect(yield* PluginHost.make(plugin, "test"))
return (yield* catalog.get(providerID))?.settings?.baseURL
})
describe("DatabricksPlugin", () => {
it.effect("fills the base URL from a bare host", () =>
@@ -5,6 +5,7 @@ import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { GoogleVertexPlugin } from "@opencode/core/plugin/provider/google-vertex"
import { Provider } from "@opencode/core/provider"
import { withEnv } from "../fixture/env"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -21,27 +22,6 @@ function required<T>(value: T | undefined): T {
return value
}
function withEnv<A, E, R>(vars: Record<string, string | undefined>, effect: () => Effect.Effect<A, E, R>) {
return Effect.acquireUseRelease(
Effect.sync(() => {
const previous = Object.fromEntries(Object.keys(vars).map((key) => [key, process.env[key]]))
Object.entries(vars).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
})
return previous
}),
effect,
(previous) =>
Effect.sync(() =>
Object.entries(previous).forEach(([key, value]) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}),
),
)
}
describe("GoogleVertexPlugin", () => {
it.effect("ignores OpenAI-compatible providers that are not Google Vertex", () =>
Effect.gen(function* () {
@@ -10,6 +10,7 @@ import { Provider } from "@opencode/core/provider"
import { Document, Event, Info } from "@opencode/schema/config"
import { describe, expect, test } from "bun:test"
import { Duration, Effect, Layer, Schema } from "effect"
import { eventually } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -22,20 +23,6 @@ const addPlugin = Effect.fn(function* (origin: string, interval: Duration.Input
yield* make(origin, interval).effect(host)
})
function eventually<A>(
effect: Effect.Effect<A>,
predicate: (value: A) => boolean,
remaining = 3000,
): Effect.Effect<A, Error> {
return Effect.gen(function* () {
const value = yield* effect
if (predicate(value)) return value
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
return yield* eventually(effect, predicate, remaining - 1)
})
}
describe("LMStudioPlugin", () => {
test("is registered as a built-in provider plugin", () => {
expect(LMStudioPlugin.id).toBe("opencode.provider.lmstudio")
@@ -12,6 +12,7 @@ import { Provider } from "@opencode/core/provider"
import { Document, Event, Info } from "@opencode/schema/config"
import { describe, expect } from "bun:test"
import { Duration, Effect, Layer, Schema } from "effect"
import { eventually } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -25,20 +26,6 @@ const addPlugin = Effect.fn(function* (origin: string, interval: Duration.Input
yield* make(origin, interval).effect(host)
})
function eventually<A>(
effect: Effect.Effect<A>,
predicate: (value: A) => boolean,
remaining = 3000,
): Effect.Effect<A, Error> {
return Effect.gen(function* () {
const value = yield* effect
if (predicate(value)) return value
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
return yield* eventually(effect, predicate, remaining - 1)
})
}
describe("OllamaPlugin", () => {
it.live("skips unconfigured default local discovery when the location has no local execution plane", () =>
Effect.gen(function* () {
@@ -29,6 +29,7 @@ import { Session } from "@opencode/core/session"
import { WebSearch } from "@opencode/core/websearch"
import { withEnv } from "../fixture/env"
import { drain } from "../lib/clock"
import { eventually } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -120,20 +121,6 @@ function required<T>(value: T | undefined): T {
return value
}
function eventually<A, E>(
effect: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
remaining = 1000,
): Effect.Effect<A, E | Error> {
return Effect.gen(function* () {
const value = yield* effect
if (predicate(value)) return value
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
return yield* eventually(effect, predicate, remaining - 1)
})
}
const cost = (input: number, output = 0) => [
{
input: Money.USDPerMillionTokens.make(input),
@@ -10,6 +10,7 @@ import { Provider } from "@opencode/core/provider"
import { Document, Event, Info } from "@opencode/schema/config"
import { describe, expect } from "bun:test"
import { Duration, Effect, Layer, Schema } from "effect"
import { eventually } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -22,20 +23,6 @@ const addPlugin = Effect.fn(function* (origin: string, interval: Duration.Input
yield* make(origin, interval).effect(host)
})
function eventually<A>(
effect: Effect.Effect<A>,
predicate: (value: A) => boolean,
remaining = 3000,
): Effect.Effect<A, Error> {
return Effect.gen(function* () {
const value = yield* effect
if (predicate(value)) return value
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
return yield* eventually(effect, predicate, remaining - 1)
})
}
const remoteModel = (id: string, max_model_len = 32_768, owned_by = "vllm") => ({
id,
object: "model",
@@ -142,10 +129,7 @@ describe("VLLMPlugin", () => {
expect(yield* modelState.get(providerID, Model.ID.make("second-model"))).toBeUndefined()
state.failing = false
yield* eventually(
modelState.get(providerID, Model.ID.make("second-model")),
(model) => model !== undefined,
)
yield* eventually(modelState.get(providerID, Model.ID.make("second-model")), (model) => model !== undefined)
expect(yield* modelState.get(providerID, Model.ID.make("first-model"))).toBeUndefined()
}),
({ server }) => Effect.promise(() => server.stop(true)),
@@ -278,10 +262,7 @@ describe("VLLMPlugin", () => {
requests.splice(0)
yield* config.setEntries([configuration({ baseURL }), configuration({ apiKey: "next-secret" })])
yield* bus.publish(Event.Updated, {})
yield* eventually(
providers.get(providerID),
(provider) => provider?.settings?.apiKey === "next-secret",
)
yield* eventually(providers.get(providerID), (provider) => provider?.settings?.apiKey === "next-secret")
expect(requests).toContainEqual({ authorization: "Bearer next-secret", path: "/proxy/health" })
expect(requests).toContainEqual({ authorization: "Bearer next-secret", path: "/proxy/v1/models" })
}),
@@ -31,6 +31,7 @@ import { Effect } from "effect"
import { FakeClaude } from "./lib/fake-claude"
import { FakeIO } from "./lib/fake-io"
import { TestSessions } from "./lib/sessions"
import { eventually } from "../../../lib/eventually"
import { testEffect } from "../../../lib/effect"
import { PluginTestLayer } from "../../fixture"
@@ -77,21 +78,6 @@ const connectionStatus = Effect.gen(function* () {
return integration?.connections[0]?.status
})
// Bounded by elapsed time rather than attempts, so a busy machine still fits.
function eventually<A, R>(
effect: Effect.Effect<A, never, R>,
predicate: (value: A) => boolean,
deadline = Date.now() + 10_000,
): Effect.Effect<A, Error, R> {
return Effect.gen(function* () {
const value = yield* effect
if (predicate(value)) return value
if (Date.now() > deadline) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
return yield* eventually(effect, predicate, deadline)
})
}
function find(models: readonly Model.Info[], id: string) {
const model = models.find((model) => model.id === id)
if (!model) throw new Error(`Expected model ${id}`)
+2 -10
View File
@@ -1,5 +1,5 @@
import { describe, expect } from "bun:test"
import { Deferred, Effect, Fiber, Layer, Schedule, Stream } from "effect"
import { Deferred, Effect, Fiber, Layer, Stream } from "effect"
import { Agent } from "@opencode/core/agent"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { LayerNode } from "@opencode/util/effect/layer-node"
@@ -10,6 +10,7 @@ import { Document, Event } from "@opencode/schema/config"
import { AbsolutePath } from "@opencode/core/schema"
import { Skill } from "@opencode/core/skill"
import { SkillInstructions } from "@opencode/core/skill/instructions"
import { waitUntil } from "./lib/eventually"
import { testEffect } from "./lib/effect"
import { readInitial } from "./lib/instructions"
import { registerIntegrationPolicy, setOrganizationPolicy } from "./fixture/policy"
@@ -270,12 +271,3 @@ describe("Skill", () => {
}),
)
})
const waitUntil = (condition: Effect.Effect<boolean>) =>
condition.pipe(
Effect.filterOrFail(
(ready) => ready,
() => new Error("Skill policy was not applied"),
),
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
)