Skip to content

Commit 0e97ae9

Browse files
fix: address fx provider review findings
Co-authored-by: maria <[email protected]>
1 parent d80407a commit 0e97ae9

12 files changed

Lines changed: 183 additions & 35 deletions

File tree

‎apps/server/src/provider/Drivers/FxDriver.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ export const FxDriver: ProviderDriver<FxSettings, FxDriverEnv> = {
142142
new ProviderDriverError({
143143
driver: DRIVER_KIND,
144144
instanceId,
145-
detail: `Failed to build Fx snapshot: ${cause.message ?? String(cause)}`,
145+
detail: "Failed to build the fx provider snapshot.",
146146
cause,
147147
}),
148148
),

‎apps/server/src/provider/Layers/FxAdapter.ts‎

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import * as Effect from "effect/Effect";
1919
import * as Exit from "effect/Exit";
2020
import * as Fiber from "effect/Fiber";
2121
import * as FileSystem from "effect/FileSystem";
22-
import * as Option from "effect/Option";
22+
2323
import * as Path from "effect/Path";
2424
import * as PubSub from "effect/PubSub";
2525
import * as Ref from "effect/Ref";
@@ -113,6 +113,11 @@ interface FxSessionContext {
113113
stopped: boolean;
114114
}
115115

116+
interface ThreadLockEntry {
117+
readonly semaphore: Semaphore.Semaphore;
118+
readonly users: number;
119+
}
120+
116121
function settlePendingApprovalsAsCancelled(
117122
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
118123
): Effect.Effect<void> {
@@ -232,7 +237,7 @@ export function makeFxAdapter(fxSettings: FxSettings, options?: FxAdapterLiveOpt
232237
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
233238

234239
const sessions = new Map<ThreadId, FxSessionContext>();
235-
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
240+
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, ThreadLockEntry>());
236241
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
237242

238243
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
@@ -263,26 +268,42 @@ export function makeFxAdapter(fxSettings: FxSettings, options?: FxAdapterLiveOpt
263268
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
264269
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
265270

266-
const getThreadSemaphore = (threadId: string) =>
271+
const acquireThreadSemaphore = (threadId: string) =>
267272
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
268-
const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
269-
current.get(threadId),
273+
const existing = current.get(threadId);
274+
if (existing) {
275+
const next = new Map(current);
276+
next.set(threadId, { ...existing, users: existing.users + 1 });
277+
return Effect.succeed([existing.semaphore, next] as const);
278+
}
279+
return Semaphore.make(1).pipe(
280+
Effect.map((semaphore) => {
281+
const next = new Map(current);
282+
next.set(threadId, { semaphore, users: 1 });
283+
return [semaphore, next] as const;
284+
}),
270285
);
271-
return Option.match(existing, {
272-
onNone: () =>
273-
Semaphore.make(1).pipe(
274-
Effect.map((semaphore) => {
275-
const next = new Map(current);
276-
next.set(threadId, semaphore);
277-
return [semaphore, next] as const;
278-
}),
279-
),
280-
onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
281-
});
286+
});
287+
288+
const releaseThreadSemaphore = (threadId: string) =>
289+
SynchronizedRef.update(threadLocksRef, (current) => {
290+
const existing = current.get(threadId);
291+
if (!existing) return current;
292+
const next = new Map(current);
293+
if (existing.users <= 1) {
294+
next.delete(threadId);
295+
} else {
296+
next.set(threadId, { ...existing, users: existing.users - 1 });
297+
}
298+
return next;
282299
});
283300

284301
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
285-
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
302+
Effect.acquireUseRelease(
303+
acquireThreadSemaphore(threadId),
304+
(semaphore) => semaphore.withPermit(effect),
305+
() => releaseThreadSemaphore(threadId),
306+
);
286307

287308
const settlePromptInFlight = (
288309
threadId: ThreadId,
@@ -563,7 +584,6 @@ export function makeFxAdapter(fxSettings: FxSettings, options?: FxAdapterLiveOpt
563584
const acp = yield* makeFxAcpRuntime({
564585
fxSettings,
565586
...(options?.environment ? { environment: options.environment } : {}),
566-
childProcessSpawner,
567587
cwd,
568588
...(resumeSessionId ? { resumeSessionId } : {}),
569589
clientInfo: { name: "t3-code", version: "0.0.0" },
@@ -586,14 +606,15 @@ export function makeFxAdapter(fxSettings: FxSettings, options?: FxAdapterLiveOpt
586606
: {}),
587607
...acpNativeLoggers,
588608
}).pipe(
609+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
589610
Effect.provideService(Crypto.Crypto, crypto),
590611
Effect.provideService(Scope.Scope, sessionScope),
591612
Effect.mapError(
592613
(cause) =>
593614
new ProviderAdapterProcessError({
594615
provider: PROVIDER,
595616
threadId: input.threadId,
596-
detail: cause.message,
617+
detail: "Failed to start the fx ACP runtime.",
597618
cause,
598619
}),
599620
),
@@ -919,7 +940,7 @@ export function makeFxAdapter(fxSettings: FxSettings, options?: FxAdapterLiveOpt
919940
new ProviderAdapterRequestError({
920941
provider: PROVIDER,
921942
method: "session/prompt",
922-
detail: cause.message,
943+
detail: "Failed to read an fx prompt attachment.",
923944
cause,
924945
}),
925946
),

‎apps/server/src/provider/Layers/FxProvider.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
import * as NodePath from "node:path";
3+
import * as NodeURL from "node:url";
4+
15
import * as NodeServices from "@effect/platform-node/NodeServices";
26
import { describe, expect, it } from "@effect/vitest";
37
import * as Effect from "effect/Effect";
@@ -9,6 +13,8 @@ import { FxSettings } from "@t3tools/contracts";
913
import { buildInitialFxProviderSnapshot, checkFxProviderStatus } from "./FxProvider.ts";
1014

1115
const decodeFxSettings = Schema.decodeSync(FxSettings);
16+
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
17+
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
1218

1319
function shellSingleQuote(value: string): string {
1420
return `'${value.replaceAll("'", `'"'"'`)}'`;
@@ -99,7 +105,6 @@ it.layer(NodeServices.layer)("checkFxProviderStatus", (it) => {
99105
const path = yield* Path.Path;
100106
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-fx-acp-success-" });
101107
const fxPath = path.join(dir, "fx");
102-
const mockAgentPath = path.join(process.cwd(), "apps/server/scripts/acp-mock-agent.ts");
103108
yield* fs.writeFileString(
104109
fxPath,
105110
[

‎apps/server/src/provider/Layers/FxProvider.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,11 +125,9 @@ const discoverFxModelsViaAcp = (
125125
environment: NodeJS.ProcessEnv = process.env,
126126
) =>
127127
Effect.gen(function* () {
128-
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
129128
const acp = yield* makeFxAcpRuntime({
130129
fxSettings,
131130
environment,
132-
childProcessSpawner,
133131
cwd: process.cwd(),
134132
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
135133
});

‎apps/server/src/provider/Layers/ProviderRegistry.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1740,6 +1740,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
17401740
"claudeAgent",
17411741
"codex",
17421742
"cursor",
1743+
"fx",
17431744
"grok",
17441745
"opencode",
17451746
]);

‎apps/server/src/provider/acp/FxAcpSupport.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,20 @@ describe("applyFxAcpModelSelection", () => {
7777
}),
7878
);
7979

80+
it.effect("uses fx's active model for the default sentinel", () =>
81+
Effect.gen(function* () {
82+
const { runtime, modelCalls } = makeRecordingRuntime();
83+
const result = yield* applyFxAcpModelSelection({
84+
runtime,
85+
currentModelId: "provider-active-model",
86+
requestedModelId: "default",
87+
mapError: (cause) => cause.message,
88+
});
89+
expect(modelCalls).toEqual([]);
90+
expect(result).toBe("provider-active-model");
91+
}),
92+
);
93+
8094
it.effect("skips the model update when no model is requested", () =>
8195
Effect.gen(function* () {
8296
const { runtime, modelCalls } = makeRecordingRuntime();

‎apps/server/src/provider/acp/FxAcpSupport.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ interface FxAcpRuntimeInput extends Omit<
1414
AcpSessionRuntime.AcpSessionRuntimeOptions,
1515
"authMethodId" | "clientCapabilities" | "spawn"
1616
> {
17-
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
1817
readonly fxSettings: FxAcpRuntimeFxSettings | null | undefined;
1918
readonly environment?: NodeJS.ProcessEnv;
2019
}
@@ -37,17 +36,16 @@ export const makeFxAcpRuntime = (
3736
): Effect.Effect<
3837
AcpSessionRuntime.AcpSessionRuntime["Service"],
3938
EffectAcpErrors.AcpError,
40-
Crypto.Crypto | Scope.Scope
39+
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
4140
> =>
4241
Effect.gen(function* () {
42+
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4343
const acpContext = yield* Layer.build(
4444
AcpSessionRuntime.layer({
4545
...input,
4646
spawn: buildFxAcpSpawnInput(input.fxSettings, input.cwd, input.environment),
4747
}).pipe(
48-
Layer.provide(
49-
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
50-
),
48+
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner)),
5149
),
5250
);
5351
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
@@ -80,6 +78,9 @@ export function applyFxAcpModelSelection<E>(input: {
8078
readonly requestedModelId: string | undefined;
8179
readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
8280
}): Effect.Effect<string | undefined, E> {
81+
if (input.requestedModelId === "default") {
82+
return Effect.succeed(input.currentModelId);
83+
}
8384
const shouldSwitchModel =
8485
input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
8586
if (!shouldSwitchModel) {

‎apps/server/src/textGeneration/FxTextGeneration.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,55 @@ it.layer(FxTextGenerationTestLayer)("FxTextGeneration", (it) => {
124124
);
125125
});
126126

127+
it.effect("sends image attachments as ACP content blocks", () => {
128+
const requestLogDir = NodeFS.mkdtempSync(
129+
NodePath.join(NodeOS.tmpdir(), "t3code-fx-image-log-"),
130+
);
131+
const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson");
132+
133+
return withFakeAcpFx(
134+
{
135+
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
136+
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ branch: "fix/image-context" }),
137+
},
138+
(textGeneration) =>
139+
Effect.gen(function* () {
140+
const { attachmentsDir } = yield* ServerConfig.ServerConfig;
141+
const attachmentId = "fx-text-image";
142+
NodeFS.mkdirSync(attachmentsDir, { recursive: true });
143+
NodeFS.writeFileSync(NodePath.join(attachmentsDir, `${attachmentId}.png`), "hello");
144+
145+
const generated = yield* textGeneration.generateBranchName({
146+
cwd: process.cwd(),
147+
message: "fix the screenshot regression",
148+
attachments: [
149+
{
150+
type: "image",
151+
id: attachmentId,
152+
name: "regression.png",
153+
mimeType: "image/png",
154+
sizeBytes: 5,
155+
},
156+
],
157+
modelSelection: createModelSelection(ProviderInstanceId.make("fx"), "composer-2"),
158+
});
159+
160+
expect(generated.branch).toBe("fix/image-context");
161+
const promptRequest = readJsonRpcRequests(requestLogPath).find(
162+
(request) => request.method === "session/prompt",
163+
);
164+
const prompt = promptRequest?.params?.prompt as
165+
| ReadonlyArray<Record<string, unknown>>
166+
| undefined;
167+
expect(prompt).toContainEqual({
168+
type: "image",
169+
data: Buffer.from("hello").toString("base64"),
170+
mimeType: "image/png",
171+
});
172+
}),
173+
);
174+
});
175+
127176
it.effect("extracts the JSON object when Fx wraps it in conversational text", () =>
128177
withFakeAcpFx(
129178
{

0 commit comments

Comments
 (0)