Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FxAdapterV2.test.ts

368 lines12.6 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, it } from "@effect/vitest";
3import {
4 MessageId,
5 NodeId,
6 ProjectId,
7 ProviderInstanceId,
8 ProviderSessionId,
9 RunAttemptId,
10 RunId,
11 type RuntimeMode,
12 ThreadId,
13} from "@t3tools/contracts";
14import { ACP_PROTOCOL } from "@t3tools/provider-acp/server/adapter";
15import { FxSettings } from "@t3tools/provider-fx/settings";
16import { FX_DRIVER_KIND, makeFxAdapterV2 } from "@t3tools/provider-fx/testing";
17import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
18import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
19import { ProviderAdapterV2RuntimePolicy } from "@t3tools/provider-core/server/ProviderAdapter";
20import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
21import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
22import * as DateTime from "effect/DateTime";
23import * as Effect from "effect/Effect";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Path from "effect/Path";
27import * as Schema from "effect/Schema";
28import * as Stream from "effect/Stream";
29import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
30​
31import {
32 decodeAcpReplayTranscript,
33 makeAcpReplayCompletenessAssertion,
34 makeAcpReplayRuntime,
35} from "./AcpAdapterV2.testkit.ts";
36​
37const testLayer = Layer.mergeAll(
38 NodeServices.layer,
39 IdAllocator.layer,
40 McpProviderSessions.layer,
41 TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)),
42);
43​
44const SESSION_ID = "fx-session-01";
45const ENABLED_FX_SETTINGS = Schema.decodeSync(FxSettings)({ enabled: true });
46/** The model `fx status --json` reports. */
47const FX_DEFAULT_MODEL = "anthropic/claude-opus-5.5";
48const NAMED_MODEL = "anthropic/claude-sonnet-5.5";
49const CUSTOM_MODEL = "openai/gpt-6.1-sol";
50const CODEX_MODEL = "gpt-6.1-sol";
51const FX_0_0_13_MODES = ["code", "ask"];
52/** fx `main` after vercel-labs/fx#1189. */
53const FX_MAIN_MODES = ["auto", "ask", "full-access"];
54​
55type Frame = Record<string, unknown>;
56const outbound = (method: string, params: unknown = "<any>"): Frame => ({
57 type: "expect_outbound",
58 label: method,
59 frame: { kind: "request", method, params },
60});
61const answer = (method: string, result: unknown): Frame => ({
62 type: "emit_inbound",
63 label: `${method}.result`,
64 frame: { kind: "response", method, result },
65});
66​
67const select = (
68 id: string,
69 category: string,
70 currentValue: string,
71 values: ReadonlyArray<string>,
72) => ({
73 id,
74 name: id,
75 category,
76 type: "select",
77 currentValue,
78 options: values.map((value) => ({ value, name: value })),
79});
80​
81/**
82 * fx's session config as recorded from 0.0.13 (fixtures/simple), models
83 * trimmed. fx lists its backend `provider` before `model`, both with
84 * category `model`.
85 */
86const fxConfig = (input: {
87 readonly model: string;
88 readonly modes: ReadonlyArray<string>;
89 readonly mode?: string;
90 /** The session's own model list, on a backend other than the gateway. */
91 readonly models?: ReadonlyArray<string>;
92}) => [
93 select("provider", "model", "gateway", ["gateway", "codex", "grok"]),
94 select(
95 "model",
96 "model",
97 input.model,
98 input.models ?? [NAMED_MODEL, FX_DEFAULT_MODEL, "openai/gpt-5.6-sol"],
99 ),
100 select("mode", "mode", input.mode ?? "ask", input.modes),
101 select("effort", "thought_level", "xhigh", ["auto", "low", "medium", "high", "xhigh", "max"]),
102];
103​
104/**
105 * fx's reply to `session/new` or `session/load`. fx 0.0.13 reports `ask`
106 * while it enforces its saved default until a client writes the mode.
107 */
108const fxSession = (input: {
109 readonly model: string;
110 readonly modes: ReadonlyArray<string>;
111 readonly models?: ReadonlyArray<string>;
112}) => ({
113 sessionId: SESSION_ID,
114 configOptions: fxConfig(input),
115 modes: { currentModeId: "ask", availableModes: input.modes.map((id) => ({ id, name: id })) },
116});
117​
118const initialize: ReadonlyArray<Frame> = [
119 outbound("initialize"),
120 answer("initialize", {
121 protocolVersion: 1,
122 agentCapabilities: {
123 loadSession: true,
124 promptCapabilities: { image: true, audio: false, embeddedContext: true },
125 },
126 agentInfo: { name: "fx", title: "fx", version: "0.0.13" },
127 authMethods: [],
128 }),
129];
130​
131/** A config write and fx's reply, which lists the session's config after it. */
132const setConfig = (
133 configId: string,
134 value: string,
135 configAfter: ReadonlyArray<unknown>,
136): ReadonlyArray<Frame> => [
137 outbound("session/set_config_option", { sessionId: SESSION_ID, configId, value }),
138 answer("session/set_config_option", { configOptions: configAfter }),
139];
140​
141/**
142 * Opens an fx session against a scripted ACP agent, which fails on any
143 * frame the script does not expect. Every scripted frame must be used.
144 */
145const openFxSession = Effect.fn("openFxSession")(function* (input: {
146 readonly scenario: string;
147 readonly frames: ReadonlyArray<Frame>;
148 readonly runtimeMode: RuntimeMode;
149 readonly model?: string;
150 /** Loads this fx session instead of creating one. */
151 readonly loadSessionId?: string;
152 /** Then starts a turn on this model. */
153 readonly turnModel?: string;
154}) {
155 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
156 const fileSystem = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158 const replayDir = yield* fileSystem.makeTempDirectoryScoped({
159 prefix: `t3-fx-${input.scenario}-`,
160 });
161 const statusPath = path.join(replayDir, "status.json");
162 const transcript = yield* decodeAcpReplayTranscript(
163 {
164 provider: FX_DRIVER_KIND,
165 protocol: ACP_PROTOCOL,
166 version: "1",
167 scenario: input.scenario,
168 entries: input.frames as never,
169 },
170 FX_DRIVER_KIND,
171 );
172 const instanceId = ProviderInstanceId.make(`fx-${input.scenario}`);
173 const adapter = yield* makeFxAdapterV2({
174 instanceId,
175 settings: ENABLED_FX_SETTINGS,
176 environment: {},
177 selfInvocation: yield* resolveSelfInvocation(),
178 defaultModel: Effect.succeed(FX_DEFAULT_MODEL),
179 makeRuntime: makeAcpReplayRuntime({
180 transcript,
181 statusPath,
182 scriptPath: yield* path.fromFileUrl(
183 new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
184 ),
185 childProcessSpawner,
186 fileSystem,
187 }),
188 });
189 const threadId = ThreadId.make(`thread-fx-${input.scenario}`);
190 // The thread's effort matches the session's, so no effort write is scripted.
191 const selectionOn = (model: string) => ({
192 instanceId,
193 model,
194 options: [{ id: "effort", value: "xhigh" }],
195 });
196 const modelSelection = selectionOn(input.model ?? "default");
197 const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
198 runtimeMode: input.runtimeMode,
199 interactionMode: "default",
200 cwd: replayDir,
201 });
202 yield* Effect.gen(function* () {
203 const session = yield* adapter.openSession({
204 threadId,
205 providerSessionId: ProviderSessionId.make(`provider-session-fx-${input.scenario}`),
206 modelSelection,
207 runtimePolicy,
208 ...(input.loadSessionId === undefined ? {} : { initialNativeThreadId: input.loadSessionId }),
209 });
210 if (input.turnModel === undefined) return;
211 const providerThread = yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
212 const now = yield* DateTime.now;
213 const turnSelection = selectionOn(input.turnModel);
214 yield* session.startTurn({
215 appThread: {
216 createdBy: "user",
217 creationSource: "web",
218 id: threadId,
219 projectId: ProjectId.make(`project:${threadId}`),
220 title: "fx adapter test",
221 providerInstanceId: instanceId,
222 modelSelection: turnSelection,
223 runtimeMode: runtimePolicy.runtimeMode,
224 interactionMode: "default",
225 branch: null,
226 worktreePath: null,
227 activeProviderThreadId: providerThread.id,
228 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
229 forkedFrom: null,
230 createdAt: now,
231 updatedAt: now,
232 archivedAt: null,
233 settledOverride: null,
234 settledAt: null,
235 lastVisitedAt: null,
236 deletedAt: null,
237 },
238 threadId,
239 runId: RunId.make(`run:${threadId}:1`),
240 runOrdinal: 1,
241 providerTurnOrdinal: 1,
242 attemptId: RunAttemptId.make(`attempt:${threadId}:1`),
243 rootNodeId: NodeId.make(`node:${threadId}:1`),
244 providerThread,
245 message: {
246 createdBy: "user",
247 creationSource: "web",
248 messageId: MessageId.make(`message:${threadId}:1`),
249 text: "Say hello",
250 attachments: [],
251 },
252 modelSelection: turnSelection,
253 runtimePolicy,
254 });
255 yield* session.events.pipe(
256 Stream.takeUntil((event) => event.type === "turn.terminal"),
257 Stream.runDrain,
258 );
259 }).pipe(Effect.scoped);
260 yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
261});
262​
263describe("FxAdapterV2", () => {
264 it.effect("runs Auto as fx's `code` mode on 0.0.13 and as `auto` where fx advertises it", () =>
265 Effect.forEach(
266 [
267 { scenario: "auto-0-0-13", modes: FX_0_0_13_MODES, written: "code" },
268 { scenario: "auto-main", modes: FX_MAIN_MODES, written: "auto" },
269 ],
270 ({ scenario, modes, written }) =>
271 openFxSession({
272 scenario,
273 runtimeMode: "auto",
274 frames: [
275 ...initialize,
276 outbound("session/new", { cwd: "<workspace>", mcpServers: "<any>" }),
277 answer("session/new", fxSession({ model: FX_DEFAULT_MODEL, modes })),
278 ...setConfig(
279 "mode",
280 written,
281 fxConfig({ model: FX_DEFAULT_MODEL, modes, mode: written }),
282 ),
283 ],
284 }),
285 { discard: true },
286 ).pipe(Effect.provide(testLayer), Effect.scoped),
287 );
288​
289 it.effect("puts a loaded session that ran a named model back on fx's default for Default", () =>
290 openFxSession({
291 scenario: "default-model",
292 runtimeMode: "approval-required",
293 model: "default",
294 loadSessionId: SESSION_ID,
295 frames: [
296 ...initialize,
297 outbound("session/load"),
298 answer("session/load", fxSession({ model: NAMED_MODEL, modes: FX_0_0_13_MODES })),
299 // Config id `model`, never fx's `provider`, and never T3's "default".
300 ...setConfig(
301 "model",
302 FX_DEFAULT_MODEL,
303 fxConfig({ model: FX_DEFAULT_MODEL, modes: FX_0_0_13_MODES }),
304 ),
305 // Written on load even though fx reports ask.
306 ...setConfig("mode", "ask", fxConfig({ model: FX_DEFAULT_MODEL, modes: FX_0_0_13_MODES })),
307 ],
308 }).pipe(Effect.provide(testLayer), Effect.scoped),
309 );
310​
311 // `fx status` names the gateway default, but this loaded session runs on
312 // Codex, whose catalog lacks it; fx would refuse the write and the thread
313 // could not start.
314 it.effect("keeps the session's model when its backend lacks fx's default", () =>
315 openFxSession({
316 scenario: "default-other-backend",
317 runtimeMode: "approval-required",
318 model: "default",
319 loadSessionId: SESSION_ID,
320 frames: [
321 ...initialize,
322 outbound("session/load"),
323 answer(
324 "session/load",
325 fxSession({ model: CODEX_MODEL, models: [CODEX_MODEL], modes: FX_0_0_13_MODES }),
326 ),
327 ...setConfig(
328 "mode",
329 "ask",
330 fxConfig({ model: CODEX_MODEL, models: [CODEX_MODEL], modes: FX_0_0_13_MODES }),
331 ),
332 ],
333 }).pipe(Effect.provide(testLayer), Effect.scoped),
334 );
335​
336 // fx 0.0.13's gateway takes any model id (src/acp/server.zig
337 // handleSetConfigOption) and lists the current one even when its catalog
338 // does not, so a custom model reaches fx instead of running on another,
339 // and switching back afterwards leaves it again.
340 it.effect("sends a custom model fx does not list, and leaves it for Default", () =>
341 openFxSession({
342 scenario: "custom-model",
343 runtimeMode: "approval-required",
344 model: CUSTOM_MODEL,
345 turnModel: "default",
346 frames: [
347 ...initialize,
348 outbound("session/new"),
349 answer("session/new", fxSession({ model: FX_DEFAULT_MODEL, modes: FX_0_0_13_MODES })),
350 ...setConfig(
351 "model",
352 CUSTOM_MODEL,
353 fxConfig({ model: CUSTOM_MODEL, modes: FX_0_0_13_MODES }),
354 ),
355 ...setConfig("mode", "ask", fxConfig({ model: CUSTOM_MODEL, modes: FX_0_0_13_MODES })),
356 // Back on Default, which the session started on: fx runs the custom
357 // model now, so the write must go out again.
358 ...setConfig(
359 "model",
360 FX_DEFAULT_MODEL,
361 fxConfig({ model: FX_DEFAULT_MODEL, modes: FX_0_0_13_MODES }),
362 ),
363 outbound("session/prompt"),
364 answer("session/prompt", { stopReason: "end_turn" }),
365 ],
366 }).pipe(Effect.provide(testLayer), Effect.scoped),
367 );
368});