GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(ai): add first-class TestLLM controls (#45828) · anomalyco/opencode@0d42e76

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • ai
      • README.md
      • src
        • testing.ts
      • test
        • exports.test.ts
        • testing.test.ts
      • tsconfig.types.json
    • core/test
      • generate.test.ts
      • session-step.test.ts
    • sdk/test
      • embedded.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/ai/README.md‎

Copy file name to clipboardExpand all lines: packages/ai/README.md
+29-11Lines changed: 29 additions & 11 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -214,22 +214,40 @@ the requests sent by code under test:
214214
import { Effect } from "effect"
215215
import { TestLLM } from "@opencode-ai/ai/testing"
216216

217-
const testLLM = TestLLM.layer({
218-
fallback: TestLLM.text("Hello from the test model", "text-1"),
219-
})
220-
221-
// TestLLM.clientLayer provides LLMClient.Service and consumes TestLLM.Service.
222217
const programWithTestClient = Effect.gen(function* () {
218+
const test = yield* TestLLM.Test
219+
yield* test.push(TestLLM.text("Hello from the test model", "text-1"))
223220
const result = yield* program
224-
const test = yield* TestLLM.Service
225-
console.log(test.requests)
221+
console.log(yield* test.requests())
226222
return result
227-
}).pipe(Effect.provide(TestLLM.clientLayer), Effect.provide(testLLM))
223+
}).pipe(Effect.provide(TestLLM.testLayer()))
228224
```
229225

230-
`TestLLM.push(...)` scripts one-shot responses, `TestLLM.always(...)` changes the fallback, and
231-
`TestLLM.wait(...)` lets concurrent tests wait until a request has arrived. Every received canonical request is
232-
available on the yielded `TestLLM.Service`.
226+
`testLayer()` provides the same object under `LLMClient.Service` and `TestLLM.Test`. Production consumes the
227+
normal client; tests use the additional controls. Each layer build has fresh state.
228+
229+
- `test.push(...)` queues one-shot responses in execution order. Each argument is one response.
230+
- `test.always(response)` installs a repeatable fallback. The layer's `fallback` option sets its initial value.
231+
- `test.serve(request => response)` installs a request-dependent fallback. `always` and `serve` replace each
232+
other without changing queued replies; queued replies take precedence.
233+
- `test.requests()` returns an array snapshot. `transformRequest` changes only the recorded observation;
234+
`serve` receives the original canonical request.
235+
- `test.wait(count)` waits for request arrivals, not output or completion, and supports concurrent waiters.
236+
- `test.gate()` returns a scoped gate with countable `started` notifications and a `release` Effect. Release
237+
unblocks all requests captured by that gate; closing its scope also releases it. Effect-aware test runners
238+
already provide Scope.
239+
240+
Constructing `stream()` or `generate()` does not record a request, invoke a responder, or consume a script.
241+
Each execution does. An exhausted queue without a fallback defects immediately rather than waiting for a
242+
future reply.
243+
244+
Responses remain canonical event arrays or arbitrary `Stream<LLMEvent, AIError>` values. The client consumes
245+
supplied streams directly, preserving failure identity, finalizers, incomplete output, and post-finish tails;
246+
it does not repair or truncate them.
247+
248+
The published legacy `Service`, `layer`, `clientLayer`, and module-level controls remain available as adapters
249+
over the same implementation, including the legacy live `requests` array. New tests should use `Test` and
250+
`testLayer`.
233251

234252
## Caching
235253

Collapse file

‎packages/ai/src/testing.ts‎

Copy file name to clipboardExpand all lines: packages/ai/src/testing.ts
+104-53Lines changed: 104 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export * as TestLLM from "./testing.js"
22

3-
import { LLMClient, type Interface as LLMClientShape } from "./route/client.js"
3+
import { LLMClient } from "./route/client.js"
44
import {
55
LLMEvent,
66
LLMResponse,
@@ -16,13 +16,33 @@ export type Response = readonly LLMEvent[] | Stream.Stream<LLMEvent, AIError>
1616

1717
export type Gate = Readonly<{ started: Effect.Effect<void>; release: Effect.Effect<void> }>
1818

19+
type ClientInterface = Context.Service.Shape<typeof LLMClient.Service>
20+
21+
export type Responder = (request: LLMRequest) => Response
22+
23+
export interface TestInterface extends ClientInterface {
24+
/** Returns a snapshot of requests observed at execution time. */
25+
readonly requests: () => Effect.Effect<readonly LLMRequest[]>
26+
readonly push: (...responses: readonly Response[]) => Effect.Effect<void>
27+
/** Replaces the fallback without changing queued responses. */
28+
readonly always: (response: Response) => Effect.Effect<void>
29+
/** Answers requests after the one-shot queue is exhausted; receives the original request. */
30+
readonly serve: (responder: Responder) => Effect.Effect<void>
31+
/** Waits for request arrivals, not output or completion. */
32+
readonly wait: (count: number) => Effect.Effect<void>
33+
readonly gate: () => Effect.Effect<Gate, never, Scope.Scope>
34+
}
35+
36+
export class Test extends Context.Service<Test, TestInterface>()("@opencode/ai/TestLLM/Test") {}
37+
38+
/** @deprecated Use TestInterface through Test and testLayer. */
1939
export interface Interface {
2040
readonly requests: LLMRequest[]
2141
readonly push: (...responses: readonly Response[]) => Effect.Effect<void>
2242
readonly always: (response: Response) => Effect.Effect<void>
2343
readonly wait: (count: number) => Effect.Effect<void>
2444
readonly gate: Effect.Effect<Gate, never, Scope.Scope>
25-
readonly client: LLMClientShape
45+
readonly client: ClientInterface
2646
}
2747

2848
export interface LayerOptions {
@@ -31,6 +51,7 @@ export interface LayerOptions {
3151
readonly fallback?: Response
3252
}
3353

54+
/** @deprecated Use Test and testLayer for normal client methods and test controls. */
3455
export class Service extends Context.Service<Service, Interface>()("@opencode/ai/TestLLM") {}
3556

3657
export const complete = (
@@ -80,59 +101,64 @@ export const hangAfter = (...events: readonly LLMEvent[]) => Stream.concat(Strea
80101

81102
const toStream = (response: Response) => (Stream.isStream(response) ? response : Stream.fromIterable(response))
82103

83-
export const layer = (options: LayerOptions = {}) =>
84-
Layer.effect(
85-
Service,
86-
Effect.gen(function* () {
87-
const requests: LLMRequest[] = []
88-
const responses: Response[] = []
89-
let started = Deferred.makeUnsafe<void>()
90-
let fallback = options.fallback
91-
let activeGate: { readonly started: Queue.Queue<void>; readonly release: Latch.Latch } | undefined
92-
const wait = (count: number): Effect.Effect<void> =>
93-
Effect.suspend(() =>
94-
requests.length >= count ? Effect.void : Deferred.await(started).pipe(Effect.andThen(wait(count))),
95-
)
96-
97-
const stream = ((request: LLMRequest) => {
98-
requests.push(options.transformRequest?.(request) ?? request)
104+
const make = (options: LayerOptions) =>
105+
Effect.sync(() => {
106+
const requests: LLMRequest[] = []
107+
const responses: Response[] = []
108+
let started = Deferred.makeUnsafe<void>()
109+
let fallback: Response | Responder | undefined = options.fallback
110+
let activeGate: { readonly started: Queue.Queue<void>; readonly release: Latch.Latch } | undefined
111+
const wait = (count: number): Effect.Effect<void> =>
112+
Effect.suspend(() =>
113+
requests.length >= count ? Effect.void : Deferred.await(started).pipe(Effect.andThen(wait(count))),
114+
)
115+
116+
const stream: ClientInterface["stream"] = (request) =>
117+
Stream.suspend(() => {
118+
const count = requests.push(options.transformRequest?.(request) ?? request)
99119
const waiting = started
100120
started = Deferred.makeUnsafe()
101-
Deferred.doneUnsafe(waiting, Effect.void)
102-
const response = responses.shift() ?? fallback
103-
if (!response) return Stream.die(new Error(`TestLLM has no response for request ${requests.length}`))
104-
const streamed = toStream(response)
105121
const gate = activeGate
106-
if (!gate) return streamed
107-
return Stream.unwrap(
108-
Queue.offer(gate.started, undefined).pipe(Effect.andThen(gate.release.await), Effect.as(streamed)),
109-
)
110-
}) as LLMClientShape["stream"]
111-
const client = LLMClient.Service.of({
112-
stream,
113-
generate: (request) =>
114-
stream(request).pipe(
115-
Stream.runFold(LLMResponse.empty, LLMResponse.reduce),
116-
Effect.flatMap((state) => {
117-
const response = LLMResponse.complete(state)
118-
if (response) return Effect.succeed(response)
119-
return Effect.die("TestLLM response ended without a terminal finish event")
120-
}),
121-
),
122+
try {
123+
const response = responses.shift() ?? (typeof fallback === "function" ? fallback(request) : fallback)
124+
if (!response) return Stream.die(new Error(`TestLLM has no response for request ${count}`))
125+
const streamed = toStream(response)
126+
if (!gate) return streamed
127+
return Stream.unwrap(
128+
Queue.offer(gate.started, undefined).pipe(Effect.andThen(gate.release.await), Effect.as(streamed)),
129+
)
130+
} finally {
131+
// Waiters can resume synchronously; assign the reply and gate before notifying them.
132+
Deferred.doneUnsafe(waiting, Effect.void)
133+
}
122134
})
123-
124-
return Service.of({
125-
requests,
126-
push: (...input) =>
127-
Effect.sync(() => {
128-
responses.push(...input)
135+
const test = Test.of({
136+
stream,
137+
generate: (request) =>
138+
stream(request).pipe(
139+
Stream.runFold(LLMResponse.empty, LLMResponse.reduce),
140+
Effect.flatMap((state) => {
141+
const response = LLMResponse.complete(state)
142+
if (response) return Effect.succeed(response)
143+
return Effect.die("TestLLM response ended without a terminal finish event")
129144
}),
130-
always: (response) =>
131-
Effect.sync(() => {
132-
fallback = response
133-
}),
134-
wait,
135-
gate: Effect.gen(function* () {
145+
),
146+
requests: () => Effect.sync(() => [...requests]),
147+
push: (...input) =>
148+
Effect.sync(() => {
149+
responses.push(...input)
150+
}),
151+
always: (response) =>
152+
Effect.sync(() => {
153+
fallback = response
154+
}),
155+
serve: (responder) =>
156+
Effect.sync(() => {
157+
fallback = responder
158+
}),
159+
wait,
160+
gate: () =>
161+
Effect.gen(function* () {
136162
const gate = {
137163
started: yield* Effect.acquireRelease(Queue.unbounded<void>(), Queue.shutdown),
138164
release: yield* Latch.make(),
@@ -147,11 +173,36 @@ export const layer = (options: LayerOptions = {}) =>
147173
release,
148174
}
149175
}),
150-
client,
151-
})
152-
}),
176+
})
177+
178+
return { test, requests }
179+
})
180+
181+
/** Provides one shared implementation under the normal client and test-control tags. */
182+
export const testLayer = (options: LayerOptions = {}) =>
183+
Layer.effectContext(
184+
Effect.map(make(options), (implementation) =>
185+
Context.make(LLMClient.Service, implementation.test).pipe(Context.add(Test, implementation.test)),
186+
),
187+
)
188+
189+
/** @deprecated Use testLayer; retained for published callers of the legacy control interface. */
190+
export const layer = (options: LayerOptions = {}) =>
191+
Layer.effect(
192+
Service,
193+
Effect.map(make(options), (implementation) =>
194+
Service.of({
195+
requests: implementation.requests,
196+
push: implementation.test.push,
197+
always: implementation.test.always,
198+
wait: implementation.test.wait,
199+
gate: implementation.test.gate(),
200+
client: implementation.test,
201+
}),
202+
),
153203
)
154204

205+
/** @deprecated testLayer provides LLMClient.Service directly. */
155206
export const clientLayer = Layer.effect(
156207
LLMClient.Service,
157208
Effect.map(Service, (service) => service.client),
Collapse file

‎packages/ai/test/exports.test.ts‎

Copy file name to clipboardExpand all lines: packages/ai/test/exports.test.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ describe("public exports", () => {
3232
expect(Provider.make).toBeFunction()
3333
expect(ProviderSubpath.make).toBe(Provider.make)
3434
expect(TestLLM.layer).toBeFunction()
35+
expect(TestLLM.testLayer).toBeFunction()
36+
expect(TestLLM.Test.of).toBeFunction()
3537
})
3638

3739
test("route barrel exposes route-authoring APIs", () => {

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.